ChunkedOutput立即在浏览器上返回响应

时间:2014-12-03 05:47:55

标签: java asynchronous jersey jersey-2.0

我正在使用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);
        }
  }

有人可以帮助我理解为什么响应不会在浏览器上出现问题以及可以采取哪些措施?

2 个答案:

答案 0 :(得分:2)

我也在为客户端处理chunkedouput响应。据我所知,

  1. 对于浏览器,你需要写更长的字符串,我不知道为什么,但似乎对于firefox,有一个缓冲区,所以除非缓冲区大小得到满足,否则浏览器不会渲染html。从我在Chrome上的测试中,您可以看到短字符串的效果。
  2. 对于chunkedInput,有一个解析器继续搜索字符串的分隔符。由于使用Jersey,ChunkedInput将无法如何拆分流。当你调用read()时,它使用解析器来拆分并返回splited substring。默认情况下,如果你写了&#39; \ r \ n&#39;对于您的chunkedoutput,您应该看到客户端代码按预期运行。

答案 1 :(得分:1)

我遇到了同样的问题。写作时添加行分隔符解决了问题。

output.write(chunk + System.lineSeparator());
相关问题