40

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
  • 20,545
  • 20
  • 91
  • 102
goodmayhem
  • 3,364
  • 4
  • 16
  • 17

3 Answers3

69

You can use following code

String responseAsString = response.readEntity(String.class);
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
whoami
  • 691
  • 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
11

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,822
  • 6
  • 51
  • 89
  • For me the getEntity() method is always returning null. I had to use readEntity(). (javax.ws.rs.core.Response from JavaEE 7). – ceklock Aug 29 '23 at 21:01
-3

You could try

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