我正在使用org.glassfish.jersey.server.ChunkedOutput来获取对我的请求的分块响应。 当我通过浏览器点击URL时,不是将输出作为单独的块输出,而是立即获得所有块。 但是当我使用测试客户端命中资源时,我将输出作为单独的块。
使用的服务器:Glassfish 4.0 泽西岛版本2.13
资源方法如下:
@GET
@Path("chunk")
public ChunkedOutput<String> getChunkedResponse(@Context HttpServletRequest request) {
final ChunkedOutput<String> output = new ChunkedOutput<String>(
String.class);
new Thread() {
public void run() {
try {
Thread.sleep(2000);
String chunk;
String arr[] = { "America\r\n", "London\r\n", "Delhi\r\n", "null" };
int i = 0;
while (!(chunk = arr[i]).equals("null")) {
output.write(chunk);
i++;
Thread.sleep(2000);
}
} catch (IOException e) {
logger.error("IOException : ", e);
} catch (InterruptedException e) {
logger.error("InterruptedException : ", e);
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error("IOException IN finally : ", e);
}
}
}
}.start();
// the output will be probably returned even before
// a first chunk is written by the new thread
return output;
}
Test Client方法如下:
private static void testChunkedResponse(WebTarget target){
final Response response = target.path("restRes").path("chunk")
.request().get();
final ChunkedInput<String> chunkedInput =
response.readEntity(new GenericType<ChunkedInput<String>>() {});
String chunk;
while ((chunk = chunkedInput.read()) != null) {
logger.info("Next chunk received: " + chunk);
}
}
有人可以帮助我理解为什么响应不会在浏览器上出现问题以及可以采取哪些措施?
答案 0 :(得分:2)
我也在为客户端处理chunkedouput响应。据我所知,
答案 1 :(得分:1)
我遇到了同样的问题。写作时添加行分隔符解决了问题。
output.write(chunk + System.lineSeparator());