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

JavaJsonWeb ServicesCxfJax Rs

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

I just found a solution for jaxrs-ri-2.16 - simply use

this delivers the content as expected.

Solution 3 - Java

For my use case, none of the previous answers worked because I was writing a server-side unit test which was failing due the following error message as described in the Unable to Mock Glassfish Jersey Client Response Object question:

java.lang.IllegalStateException: Method not supported on an outbound message.
at org.glassfish.jersey.message.internal.OutboundJaxrsResponse.readEntity(OutboundJaxrsResponse.java:145)
at ...

This exception occurred on the following line of code:

String actJsonBody = actResponse.readEntity(String.class);

The fix was to turn the problem line of code into:

String actJsonBody = (String) actResponse.getEntity();

Solution 4 - Java

I also had the same issue, trying to run a unit test calling code that uses readEntity. Can't use getEntity in production code because that just returns a ByteInputStream and not the content of the body and there is no way I am adding production code that is hit only in unit tests.

My solution was to create a response and then use a Mockito spy to mock out the readEntity method:

Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);

Note that you can't use the when(mockResponse.readEntity(String.class) option because that throws the same IllegalStateException.

Hope this helps!

Solution 5 - Java

Acording with the documentation, the method getEntity in Jax rs 2.0 return a InputStream. If you need to convert to InputStream to String with JSON format, you need to cast the two formats. For example in my case, I implemented the next method:

    private String processResponse(Response response) {
	if (response.getEntity() != null) {
		try {
			InputStream salida = (InputStream) response.getEntity();
			StringWriter writer = new StringWriter();
			IOUtils.copy(salida, writer, "UTF-8");
			return writer.toString();
		} catch (IOException ex) {
			LOG.log(Level.SEVERE, null, ex);
		}
	}
	return null;
}

why I implemented this method. Because a read in differets blogs that many developers they have the same problem whit the version in jaxrs using the next methods

String output = response.readEntity(String.class)

and

String output = response.getEntity(String.class)

The first works using jersey-client from com.sun.jersey library and the second found using the jersey-client from org.glassfish.jersey.core.

This is the error that was being presented to me: org.glassfish.jersey.client.internal.HttpUrlConnector$2 cannot be cast to java.lang.String

I use the following maven dependency:

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

What I do not know is why the readEntity method does not work.I hope you can use the solution.

Carlos Cepeda

Solution 6 - Java

Realizing the revision of the code I found the cause of why the reading method did not work for me. The problem was that one of the dependencies that my project used jersey 1.x. Update the version, adjust the client and it works.

I use the following maven dependency:

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

Regards

Carlos Cepeda

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2657714View Question on Stackoverflow
Solution 1 - JavaJuned AhsanView Answer on Stackoverflow
Solution 2 - Javacol.panicView Answer on Stackoverflow
Solution 3 - JavaentpnerdView Answer on Stackoverflow
Solution 4 - JavaCheefachiView Answer on Stackoverflow
Solution 5 - JavaMonkeySoft ColombiaView Answer on Stackoverflow
Solution 6 - JavaMonkeySoft ColombiaView Answer on Stackoverflow