如何使用Jersey API从宁静的Web服务发送和接收JSON数据

@Path("/hello") public class Hello { @POST @Path("{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public JSONObject sayPlainTextHello(@PathParam("id")JSONObject inputJsonObj) { String input = (String) inputJsonObj.get("input"); String output="The input you sent is :"+input; JSONObject outputJsonObj = new JSONObject(); outputJsonObj.put("output", output); return outputJsonObj; } } 

这是我的webservice(我正在使用Jersey API)。 但我无法找到一种方法从java rest客户端调用此方法来发送和接收json数据。 我尝试了以下方式来编写客户端

 ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(getBaseURI()); JSONObject inputJsonObj = new JSONObject(); inputJsonObj.put("input", "Value"); System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).post(JSONObject.class,JSONObject.class)); 

但这显示以下错误

 Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class java.lang.Class, and MIME media type, application/octet-stream, was not found 

您对@PathParam的使用不正确。 它不遵循这里 javadoc中记录的这些要求。 我相信你只想发布JSON实体。 您可以在资源方法中修复此问题以接受JSON实体。

 @Path("/hello") public class Hello { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception { String input = (String) inputJsonObj.get("input"); String output = "The input you sent is :" + input; JSONObject outputJsonObj = new JSONObject(); outputJsonObj.put("output", output); return outputJsonObj; } } 

而且,您的客户端代码应如下所示:

  ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); client.addFilter(new LoggingFilter()); WebResource service = client.resource(getBaseURI()); JSONObject inputJsonObj = new JSONObject(); inputJsonObj.put("input", "Value"); System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj)); 

对我来说参数(JSONObject inputJsonObj)无效。 我正在使用jersey2. *因此我觉得这是

java(Jax-rs)和Angular方式

我希望对像我这样使用JAVA Rest和AngularJS的人有帮助。

 @POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.APPLICATION_JSON) public Map methodName(String data) throws Exception { JSONObject recoData = new JSONObject(data); //Do whatever with json object } 

客户端我使用AngularJS

 factory.update = function () { data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]} data= JSON.stringify(data);//Convert object to string var d = $q.defer(); $http({ method: 'POST', url: 'REST/webApp/update', headers: {'Content-Type': 'text/plain'}, data:data }) .success(function (response) { d.resolve(response); }) .error(function (response) { d.reject(response); }); return d.promise; };