Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 553
pseudoCoder Avatar asked Aug 08 '14 05:08

pseudoCoder


People also ask

How do you get entity from response?

1 Answer. Show activity on this post. You can use: public abstract <T> T readEntity(Class<T> entityType) - Read the message entity input stream as an instance of specified Java type using a MessageBodyReader that supports mapping the message entity stream onto the requested type.

How do you return a response in Java?

The Response class is an abstract class that contains three simple methods. The getEntity() method returns the Java object you want converted into an HTTP message body. The getStatus() method returns the HTTP response code. The getMetadata() method is a MultivaluedMap of response headers.


2 Answers

You can use following code

String responseAsString = response.readEntity(String.class); 
like image 139
whoami Avatar answered Sep 18 '22 17:09

whoami


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.

like image 34
V G Avatar answered Sep 19 '22 17:09

V G