Sudhir
Sudhir

Reputation: 321

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?

Upvotes: 12

Views: 29996

Answers (4)

dvlcube
dvlcube

Reputation: 1316

In my case I'm using Jersey 1.19 and Genson got in my classpath somehow? So the accepted answer throws com.owlike.genson.stream.JsonStreamException: Readen value can not be converted to String.

My solution was to read directly from the response stream:

private String responseString(com.sun.jersey.api.client.ClientResponse response) {
        InputStream stream = response.getEntityInputStream();
        StringBuilder textBuilder = new StringBuilder();
        try (Reader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName(StandardCharsets.UTF_8.name())))) {
            int c = 0;
            while ((c = reader.read()) != -1) {
                textBuilder.append((char) c);
            }
            return textBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

Upvotes: 0

Marcio Jasinski
Marcio Jasinski

Reputation: 1479

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

Upvotes: 11

Sudhir
Sudhir

Reputation: 321

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

Upvotes: 20

Ian Lim
Ian Lim

Reputation: 4274

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

Upvotes: 0

Related Questions