Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call readEntity on a Response twice?

What I'm doing right now is resulting in a:

java.io.IOException: stream is closed

on the 2nd readEntity() since it closes the stream after the first read.

Here is what I'm doing:

Response response = target.queryParam("start", startIndex)
   .queryParam("end", end)
   .request()
   .accept(MediaType.APPLICATION_XML)
   .header(authorizationHeaderName, authorizationHeaderValue)
   .get();

String xml = response.readEntity(String.class);
ourLogger.debug(xml);


MyClass message = response.readEntity(MyClass.class); //throws IOException
like image 312
jwils Avatar asked Dec 06 '17 16:12

jwils


People also ask

What does Response readEntity do?

readEntity. 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.

What is response OK in Java?

ok. The ok read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.


1 Answers

/You can use Response#bufferEntity(), which will allow you to read the entity stream multiple times.

Response response = ...
response.bufferEntity();
String s = response.readEntity(String.class);
MyEntity me = response.readEntity(MyEntity.class);
response.close();

Update

After you read the entity with readEntity(), the result of the reading is cached and is available with the call to getEntity(). This information doesn't really answer the OP's question, but I thought it was useful information to add in.

like image 168
Paul Samsotha Avatar answered Sep 18 '22 12:09

Paul Samsotha