【问题标题】:How to send and receive JSON data from a restful webservice using Jersey API如何使用 Jersey API 从 RESTful Web 服务发送和接收 JSON 数据
【发布时间】:2013-01-14 01:30:09
【问题描述】:
@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;
    }
} 

这是我的网络服务(我正在使用 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

【问题讨论】:

  • 请通过添加 java 作为标签并在标题中包含“Jersey API”来改进您的问题。

标签: java json jersey


【解决方案1】:

您对@PathParam 的使用不正确。它不遵循 javadoc here 中记录的这些要求。我相信您只想发布 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));

【讨论】:

  • 对于未来的开发者/读者,这个答案给出了预期的输出。但是您应该导入正确的jar 文件。就我而言,我有org.json 文件和jersey 中的其他文件。所以出现错误..从here导入com.sun.jersey后运行正常...
【解决方案2】:

对我来说,参数 (JSONObject inputJsonObj) 不起作用。我正在使用球衣 2.* 因此我觉得这是

java(Jax-rs) 和 Angular 方式

希望对像我这样使用 JAVA Rest 和 AngularJS 的人有所帮助。
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> 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;
    };

【讨论】:

    【解决方案3】:

    上述问题可以通过在你的项目中添加以下依赖项来解决,因为我遇到了同样的问题。有关此解决方案的更多详细答案,请参阅链接SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.0</version>
        </dependency>
    
    
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.2</version>
        </dependency>   
    
    
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.25</version>
        </dependency>
    

    【讨论】:

    • 最后一个依赖是使用jersey rest在post call中接受json,上面两个是从rest中获取json作为响应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多