java - Jersey 客户端日志响应和 getEntity

标签 java json rest jersey jersey-client

我正在使用 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/

相关文章:

java - 将 RGB 像素转换为灰度会使暗像素呈现蓝色

javascript - 在父子结构中重新排序 JS 对象

java - Android RecyclerView : row swipe on click

java - LibGDX - 绘制到 FrameBuffer 不起作用

javascript - 将变量从 python 传递到 javascript

json - 使用 powershell 正确格式化 JSON

c# - 如何在请求后捕获 REST API 发送的响应 token ?

node.js - REST API 端点,用于通过多步骤过程更改电子邮件和更改密码

php - 西利乌斯 API : Carts conflict on login

java - 我需要数据结构来有效处理日期