reading JSON response as string using jersey client

烈酒焚心 提交于 2019-12-05 17:42:54

问题


I am using jersey client to post a file to a REST URI that returns response as json. My requirement is to read the response as is(json) to a string.

Here is the piece of code that posts the data to web service.

final ClientResponse clientResp = resource.type(
            MediaType.MULTIPART_FORM_DATA_TYPE).
            accept(MediaType.APPLICATION_JSON).
            post(ClientResponse.class, inputData);
     System.out.println("Response from news Rest Resource : " + clientResp.getEntity(String.class)); // This doesnt work.Displays nothing.

clientResp.getLength() has 281 bytes which is the size of the response, but clientResp.getEntity(String.class) returns nothing.

Any ideas what could be incorrect here?


回答1:


I was able to find solution to the problem. Just had to call bufferEntity method before getEntity(String.class). This will return response as string.

   clientResp.bufferEntity();
   String x = clientResp.getEntity(String.class);



回答2:


Although the above answer is correct, using Jersey API v2.7 it is slightly different with Response:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080");
Response response = target.path("api").path("server").path("ping").request(MediaType.TEXT_PLAIN_TYPE).get();
System.out.println("Response: " + response.getStatus() + " - " + response.readEntity(String.class));



回答3:


If you still got problem with this, you may want to consider to use rest-assured



来源:https://stackoverflow.com/questions/19557404/reading-json-response-as-string-using-jersey-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!