Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading JSON response as string using jersey client

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

Here is the piece of code that posts the data to the 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?

like image 660
Sudhir Avatar asked Oct 24 '13 05:10

Sudhir


2 Answers

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);
like image 73
Sudhir Avatar answered Oct 25 '22 18:10

Sudhir


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));
like image 22
Marcio Jasinski Avatar answered Oct 25 '22 18:10

Marcio Jasinski