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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With