34

I am making a request to an API and getting a response status code of 200.

Response of the api includes a json response.

import javax.ws.rs.core.Response;

Response response = webclient.post(SomeReqString);

How can I retrieve the json response as string from the web client response?

Nathaniel Ford
  • 18,661
  • 20
  • 81
  • 93
pseudoCoder
  • 3,274
  • 4
  • 14
  • 17

3 Answers3

61

You can use following code

String responseAsString = response.readEntity(String.class);
Subodh Joshi
  • 11,590
  • 25
  • 95
  • 188
whoami
  • 611
  • 5
  • 6
  • 1
    I tried this. The `response` object doesn't have a method called `readEntity()` – ewok Jun 21 '18 at 13:21
  • I don't know if it is deprecated by now. It at least had it once. https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Response.html#readEntity-java.lang.Class- – whoami Jun 25 '18 at 12:52
10

Try using the Response.getEntity() method, which returns an InputStream. Then, to convert your InputStream to a String, check this question. If you really need to map the JSON String to a Java entity, that consider calling directly the Response.readEntity(). Note that, if you consume the InputStream, you will probably have to process the input stream on your own.

Community
  • 1
  • 1
V G
  • 18,488
  • 6
  • 48
  • 86
-1

You could try

String responseAsString = response.getEntity().toString();