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
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);
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;
}
}
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));
If you still got problem with this, you may want to consider to use rest-assured