简体   繁体   English

Jersey客户端日志响应以及getEntity

[英]Jersey Client log response and also getEntity

I am using Jersey Client to make a REST service call. 我正在使用Jersey Client进行REST服务调用。 Now when I receive the response I want to log the json response and I also want to get the entity populated in my response bean. 现在,当我收到响应时,我想记录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);

Now the problem is that we cannot call the getEntity() two times since the stream gets consumed the first then we cannot use it second time. 现在问题是我们无法调用getEntity()两次,因为流首先被消耗,然后我们不能第二次使用它。 Hence the above code gives the exception of No content to map to Object due to end of input . 因此,上面的代码给出了No content to map to Object due to end of input的例外。 I am sure this is not a very unique requirement and would be common. 我相信这不是一个非常独特的要求,而且很常见。 So what is the best practice or method to do the same? 那么做同样的最佳做法或方法是什么?

EDIT 编辑

A working example: 一个工作的例子:

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

Ref: check the source of bufferEntity . 参考:检查bufferEntity的来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM