[英]java rest web service by post method
I am trying to do a java rest web service using "POST" method.But i am unable to access the passed parameter. 我正在尝试使用“ POST”方法来执行Java Rest Web服务。但是我无法访问传递的参数。 Here is my client part to invoke the web service. 这是我的客户端部分,用于调用Web服务。
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/wsRevDash/rest/post/testing");
Form form=new Form();
form.add("sc","pqr");
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class,form);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
And here is my java rest web service. 这是我的Java Rest Web服务。
@POST
@Path("testing")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String createDataInJSON(@FormParam("sc") String data) {
System.out.println("Hello"+data);
JSONObject jObjDevice = new JSONObject();
jObjDevice.put("Hello",data);
return jObjDevice.toJSONString();
}
When i run on SoapUI,I am getting {"Hello":null}. 当我在SoapUI上运行时,我得到{“ Hello”:null}。 Please suggest me some way to cope with this. 请建议我一些解决方法。
Try changing form
to a String
: 尝试将form
更改为String
:
String input = new Gson().toJson(form);
And pass in input
to the response: 并将input
传递给响应:
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class,input);
And amend your web service to something like: 并将您的网络服务修改为:
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Hello: " + data;
return Response.status(200).entity(result).build();
}
And you need to remove 'testing' from your initial path: 而且您需要从初始路径中删除“测试”:
WebResource webResource = client.resource("http://localhost:8080/wsRevDash/rest/post/testing"); <---- here
And include a slash before it in the web service: 并在Web服务中添加一个斜杠:
@Path("/testing")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.