如何使用输入流实体而不是分块编码创建内容长度响应?

eve*_*992 5 jax-rs jersey jersey-2.0

我需要从 Jersey 资源传输响应,但我不希望 http 响应使用Transfer-Encoding: chunked. 我提前知道流的长度,因此不需要分块编码。

    @GET
    @Path("/contentLength")
    public Response contentLength() {
        return Response.ok()
                .header("Content-Length", 10_000)
                .entity(RandomInputStream.generateBytes(10_000))
                .build());
    }
Run Code Online (Sandbox Code Playgroud)

即使我设置了 Content-Length,测试也显示响应使用分块传输编码

    @Test
    void contentLength() throws Exception {
        Response response = target().path("/contentLength").request().get();
        assertThat(response.getHeaderString("Transfer-Encoding"), Matchers.nullValue());
        assertThat(response.getHeaderString("Content-Length"), is("10000"));
    }
Run Code Online (Sandbox Code Playgroud)
Expected: null
     but: was "chunked"
Run Code Online (Sandbox Code Playgroud)

有类似的问题,但答案是错误的或需要缓冲响应,这对于大型响应来说是不可行的。对于大型响应,http 不需要分块编码,仅当响应启动时总长度未知时才需要分块编码。