reading JSON response as string using jersey client

Sudhir picture Sudhir · Oct 24, 2013 · Viewed 24.2k times · Source

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?

Answer

Sudhir picture Sudhir · Oct 26, 2013

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);