Reputation: 2845
I am trying to serialize a jax-rs Response to json string.
The response from the server is json, and I get it from jersey client with:
Response resp = target.request().method("PUT", Entity.json(payloadBean))
where payloadBean is my json request. Everything works fine but I cannot convert the resp in json string in order to log it.
If I try:
String s = EntityUtils.toString((HttpEntity) resp.getEntity());
I get:
org.glassfish.jersey.client.internal.HttpUrlConnector cannot be cast to org.apache.http.HttpEntity
By the way if I don't cast to HttpEntity, compiler says:
toString (org.apache.http.HttpEntity) in EntityUtils cannot be applied to (java.lang.Object).
My relevant imports are:
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
Any ideas?
Upvotes: 2
Views: 12981
Reputation: 2845
Finally I needed to buffer the message entity data since the stream was consumed and I was getting an error later when I was trying to re-read the response. Thus in order to log it first and then use it again I had to:
resp.bufferEntity(); //need to buffer entity, in order to read the entity multiple times from the Response's InputStream
String s = resp.readEntity(String.class);
Upvotes: 4
Reputation: 209004
Use resp.readEntity(String.class)
public abstract <T> T readEntity(Class<T> entityType)
Type Parameters:
T
- entity instance Java type.Parameters:
entityType
- the type of entity.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.
Upvotes: 6