How to retrieve JSON Response from a javax.ws.rs.core.Response response?
Asked Answered
E

3

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?

Eighteenth answered 8/8, 2014 at 5:11 Comment(0)
I
69

You can use following code

String responseAsString = response.readEntity(String.class);
Irmgardirmina answered 17/6, 2015 at 12:27 Comment(2)
I tried this. The response object doesn't have a method called readEntity()Harmonica
I don't know if it is deprecated by now. It at least had it once. docs.oracle.com/javaee/7/api/javax/ws/rs/core/…Irmgardirmina
G
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.

Godoy answered 8/8, 2014 at 10:2 Comment(1)
For me the getEntity() method is always returning null. I had to use readEntity(). (javax.ws.rs.core.Response from JavaEE 7).Bersagliere
S
-3

You could try

String responseAsString = response.getEntity().toString();
Surrealism answered 12/2, 2022 at 18:40 Comment(1)
This just leads to output like org.glassfish.jersey.client.internal.HttpUrlConnector$2@50612c54Amusement

© 2022 - 2024 — McMap. All rights reserved.