【问题标题】:Calling a @POST from Jersey从泽西岛调用 @POST
【发布时间】:2015-04-16 19:32:32
【问题描述】:

我能够在球衣上获得@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));

谁能告诉我我在这里缺少什么?

【问题讨论】:

  • 你能澄清一下你的问题吗?哪个请求特别不起作用?
  • @lunactic 第二种post方式(不指定url中的参数)

标签: java web-services rest post jersey


【解决方案1】:

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

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

如果您在编码方面遇到问题,请查看此帖子https://stackoverflow.com/a/18005711/3183976

【讨论】:

    【解决方案2】:

    试试这个。这对我有用。

    发帖方式:

    @POST
    @Path("/post2")
    public Response post2(String data) {
        System.out.println("Post method with File: " + data);
    
        return Response
                .status(200)
                .entity(data)
                .build();
    }
    

    调用方法:

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

    希望这会有所帮助。和平。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 2017-09-18
      • 2012-11-03
      • 2017-05-13
      相关资源
      最近更新 更多