How to call readEntity on a Response twice?

2019-04-29 14:48发布

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

1条回答
Anthone
2楼-- · 2019-04-29 15:10

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

查看更多
登录 后发表回答