考虑一下在Jersey 2.22.2下运行的REST代理的代码:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/foo")
public Response foo(String request) {
logger.info("Request to /foo :\n" + request);
WebTarget target = ClientBuilder.newClient().target(esbWsUrl).path("/foo");
Response response = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
// problem is in the 2 lines below
logger.info("Buffered: " + response.bufferEntity());
logger.info("Response from /foo :\n" + response.readEntity(String.class));
return response;
}
首先,我在没有response.bufferedEntity()
的情况下尝试了一下,得到了IllegalStateException
,因为response.readEntity(String.class)
是从Response
中的底层流中消费的。
当我使用response.bufferEntity()
时,我能够多次调用response.readEntity(String.class)
(缓冲似乎起作用了),但是Jersey返回的响应给出了一个零字节的响应。
$ curl -m 5 -i -X POST -d '{"input_values": "abc"}' http://localhost:9000/services/rest/foo
HTTP/1.1 200 OK
Date: Thu, 27 Oct 2016 08:18:09 GMT
Keep-Alive: timeout=20
X-Type: default
Server: nginx
Content-Type: application/json; charset=UTF-8
Content-Length: 364
curl: (28) Operation timed out after 5000 milliseconds with 0 out of 364 bytes received
这里有一些相关的文档:Response.readEntity
谁能告诉我如何在返回一个有效的Response
之前记录Response
的内容?
也许有一些我没有想到的流处理问题,或者可能是另一种将Response
实体转换为字符串(而不消耗流)的方法。
发布于 2016-11-07 13:12:37
我最终基于前一个的状态代码和实体创建了一个全新的Response
。
https://stackoverflow.com/questions/40279775
复制相似问题