java - 从 Jersey 调用@POST

标签 java web-services rest post jersey

我能够在 Jersey 上获得@GET请求,相关代码如下

服务器代码

@Path("/Text")
@GET
public String Hello() {
    System.out.println("Text Being print");
    return "Abc";
}

@POST
@Path("/post/{name}/{gender}")
public Response createDataInJSON(@PathParam("name") String data, @PathParam("gender") String data2) {
    System.out.println("Post Method 1");

    JSONObject obj = new JSONObject();
    obj.put("Name", data);
    obj.put("Gender", data2);

    return Response
            .status(200)
            .entity(obj.toJSONString())
            .build();

}

当参数在 url 中传递时,@POST 也起作用。 (如上面代码段提到的) 但是,当参数不是通过 url 发送时,它不起作用。就像下面的代码一样。

@POST
@Path("/post2")
public Response createDataInJSON2(@FormParam("action") String data) {
    System.out.println("Post Method 2 : Data received:" + data);

    JSONObject obj = new JSONObject();
    obj.put("data", data);

    return Response
            .status(200)
            .entity(obj.toJSONString())
            .build();

}

问题可能出在服务的调用方式上。

//GET call (Plain Text)
    System.out.println(service.path("Hello").accept(MediaType.TEXT_PLAIN).get(String.class));

    //POST call (Param)
    ClientResponse response = service.path("Hello/post/Dave/Male").post(ClientResponse.class);
    System.out.println(response.getEntity(String.class));

    //POST call (JSON)
    String input = "hello";

    ClientResponse response2 = service.path("Hello/post2").post(ClientResponse.class, input);
    System.out.println(response2.getEntity(String.class));

谁能告诉我我在这里错过了什么?

最佳答案

尝试在 @POST 方法上添加 @Consumes (application/x-www-form-urlencoded) createDataInJSON2 并在请求中显式添加相同的 mime 类型 service.path( "Hello/post2").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, input)

还要考虑到您的输入只是一个简单的字符串。看一下 MultivaluedMap

如果您在编码方面遇到问题,请查看这篇文章 https://stackoverflow.com/a/18005711/3183976

关于java - 从 Jersey 调用@POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28538891/

相关文章:

java - 我java我想用单个空格替换所有空格字符,同时保留所有换行符和回车符

java - 漏斗分析计算,你会如何计算一个漏斗?

java - jmeter是否使SOAP请求超时

Ajax 与 Web 服务

REST API GET/POST 使用 jquery AJAX 使用 Neo4j 图形数据库获取节点

java - Azure函数无法找到具有给定输入的方法签名

java - JFrame 和 JPanel 问题

javascript - 网络应用程序设计思想

php - RESTful API 身份验证流程

java - Nuxeo 使用 REST 使用新版本创建和更新文件