【问题标题】:CXF call REST service with JSONCXF 使用 JSON 调用 REST 服务
【发布时间】:2015-11-02 04:17:54
【问题描述】:

我有一个小问题,这是因为我对 REST 和 JSON 的体验不是很好!

不过我有这个服务

 @Path("/baseService")
 @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
 @Consumes({MediaType.APPLICATION_JSON,       MediaType.TEXT_XML,MediaType.APPLICATION_XML})
 public interface BaseService {

 @POST
 @Path("/registration")
 @Transactional
 public UserTO register(@RequestBody UserTO userto);

我想从客户端发送一个 json 来测试服务

如果我在没有 json 的情况下调用他,一切正常:

 resp=client.post(userTO);

但我不知道如何调用它发送和 json(让 spring jackson 为您将它从 json 转换为 UserTO 对象)在线阅读我尝试的一些解决方案:

client.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).query("mail", "test").query("name", "test").query("psw", "test").query("role", "cassa").query("surname", "fsddsf").query("userName", "fsdfs").post(UserTO.class);

 resp=client.accept(MediaType.APPLICATION_JSON).post(inputJsonObj);

我该怎么做?请帮忙!

【问题讨论】:

    标签: java json spring rest cxf


    【解决方案1】:

    如果您只想测试您的应用程序,那么在这种情况下,您可以使用 postman chrome 插件。

    Jakson 有 ObjectMapper 类,可以帮助您将 java obj 转换为 pojo。

    【讨论】:

      【解决方案2】:

      您可以将您的 json 作为 jsonobject (jsonObject.toString()) 传递给为您的服务端点创建的输出流。

      URL url = new URL("http://localhost:8080/yourapp/baseService/registration");
      URLConnection connection = url.openConnection();
      connection.setDoOutput(true);
      connection.setRequestProperty("Content-Type", "application/json");
      connection.setConnectTimeout(5000);
      connection.setReadTimeout(5000);
      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
      out.write(jsonObject.toString());
      out.close();
      
      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
      

      【讨论】:

      • new InputStreamReader(connection.getInputStream() 丢失字符集。对于 JSON,它应该始终是 UTF-8,所以new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF-8) 更好
      • @artbristol .. 谢谢,根据建议更新了答案。
      • 就我而言,它是 UTF_8 而不是 UTF-8
      【解决方案3】:

      这样解决,改

       resp=client.accept(MediaType.APPLICATION_JSON).post(inputJsonObj);
      

      与:

       users = client.post(inputJsonObj, UserTO.class);
      

      传递 JSON 对象和我想将其转换为的类!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多