Unable to read application/json message in Response output

Alpha picture Alpha · Sep 28, 2015 · Viewed 13.4k times · Source

I'm testing REST API and while I make GET call to retrieve resources, it's resulting into 500 Internal Server Error and in output it's returning message which has media type application/json:

[
  {
    "messageType": "Some error type",
    "messageText": "Some message text",
    "moreInfo": "Some info"
  }
]

Please make note that in above output, Json is inside []

I want to read value of messageText from above output response. I tried with -

JsonObject jsonObject = response.readEntity(JsonObject.class);

but it results in following error:

java.lang.IllegalStateException: Entity input stream has already been closed.
    at org.glassfish.jersey.message.internal.EntityInputStream.ensureNotClosed(EntityInputStream.java:225)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:830)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:783)
    at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:326)
    at org.glassfish.jersey.client.InboundJaxrsResponse$1.call(InboundJaxrsResponse.java:111)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:399)
    at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:108)

Could you please help me how can I read the message in output? I'm using Jersy library.

Answer

Tamara Aviv picture Tamara Aviv · Aug 25, 2016

I am writing automated tests for my Jersey services, which return XML objects, and I was getting this error occasionally too.

According to javaDoc, a call to readEntity closes the response entity, so when you make another readEntity call you get IllegalStateException.

Unless the supplied entity type is an input stream, this method automatically closes the an unconsumed original response entity data stream if open.

In my case, having the expression response.readEntity(String.class) in the Expressions pane in the Debug perspective caused this exception when I ran the code in Debug mode. The evaluation of the expression consumed the entity and caused it to close.