[英]Calling a @POST from 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();
}
在網址中傳遞參數時,@ 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(應用程序/ x-www-form-urlencoded),並在請求service.path("Hello/post2").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, input)
顯式添加相同的mime類型service.path("Hello/post2").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, input)
。
還請考慮您的輸入只是一個簡單的字符串。 看看類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));
希望這可以幫助。 和平。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.