我能够在球衣上得到一个@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方法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
试试这个。这对我有效。
后处理方法:
@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));
希望这能有所帮助。和平