我正在使用 Jersey Client 进行 REST 服务调用。现在,当我收到响应时,我想记录 json 响应,并且我还想让实体填充到我的响应 bean 中。
Client client = Client.create(config);
ClientResponse cr = client
.resource(endPoint)
.accept("application/json")
.get(ClientResponse.class);
clientResponse.bufferEntity();
String responseToLog = cr.getEntity(String.class);
log.debug(responseToLog);
MyResponseBean myResponse = cr.getEntity(MyResponseBean.class);
现在的问题是我们不能调用 getEntity() 两次,因为流第一次被消耗,然后我们不能第二次使用它。因此,上面的代码给出了 No content to map to Object due to end of input
的异常(exception)情况。我相信这不是一个非常独特的要求,而且很常见。那么,最好的做法或方法是什么?
最佳答案
编辑
一个工作示例:
String endPoint = "http://localhost:8080/api/places";
Client client = new Client();
ClientResponse cr = client.resource(endPoint).accept("application/json").get(ClientResponse.class);
cr.bufferEntity(); // buffer the entity (HttpInputStream->ByteArrayInputStream)
String res1 = cr.getEntity(String.class);
cr.getEntityInputStream().reset(); //reset the buffer, this is a ByteArrayInputStream
String res2 = cr.getEntity(String.class);//read again
引用:检查 bufferEntity 的来源.
关于java - Jersey 客户端日志响应和 getEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37590078/