java - 如何使用 Jersey API 从 Restful Web 服务发送和接收 JSON 数据

标签 java json jersey

@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

最佳答案

您对@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));

关于java - 如何使用 Jersey API 从 Restful Web 服务发送和接收 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14600510/

相关文章:

android - 改造返回空响应体

python - 过滤超过 2.5GB Json 文件的最快方法是什么?

java - 使用 jersey 的 JAXB 解码失败

进行简单的 sql 查询时,Java vs PHP

java - Java SE 是一个框架吗?

java - 最长公共(public)子序列差

java - 读取前刷新/清除 System.in (stdin)

ios - 创建 iOS 客户端服务器应用程序。 ASIFormDataRequest 问题

java - Twitter - 查询特定地理位置半径内的推文

java - 如何过滤 Jersey SSE 中的事件?