Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read response body in JAX-RS client from a post request

Having some sort of proxy between a mobile app and a web-service, we are puzzled by the response when issuing a post request. We receive response with status 200: OK. But we can not find/extract the JSON response body.

    Client client = ClientBuilder.newClient();     WebTarget webTarget = client.target(WEBSERVICE_BASE_LOCATION + "mobileDevices?operatorCode=KPNSCP");     String jsonString = "{\"osVersion\":\"4.1\",\"apiLevel\":16,\"devicePlatform\":\"ANDROID\"}";     Builder builder = webTarget.request();     Response response = builder.post(Entity.json(jsonString)); 

We are using JAX-RS. Can someone please provide some hints to extract the JSON body (String) from the server response?

like image 458
user2657714 Avatar asked Aug 06 '13 17:08

user2657714


People also ask

How do you get entity from response object?

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 read a response body in Java?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

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.


1 Answers

Try this:

String output = response.getEntity(String.class); 

EDIT

Thanks to @Martin Spamer to mention that it will work for Jersey 1.x jars only. For Jersey 2.x use

String output = response.readEntity(String.class); 
like image 177
Juned Ahsan Avatar answered Oct 19 '22 21:10

Juned Ahsan