Jersey/JAX-RS:在响应头中返回Content-Length而不是chunked transfer encoding

ric*_*inn 9 java rest jax-rs jaxb jersey

我正在使用Jersey来创建RESTful API资源,并ResponseBuilder生成响应.

RESTful资源的示例代码:

public class infoResource{
  @GET
  @Path("service/{id}")
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  public Response getCompany(@PathParam("id")String id) {
      //company is just a POJO.
      Company company = getCompany(id);
      return Response.status(200).entity(company).build();  
  }
}
Run Code Online (Sandbox Code Playgroud)

在响应中,它在响应头中返回分块传输编码."泽西世界"中有什么方法让它返回Content-Length标题而不是Transfer-Encoding: chunked响应标题中的标题?

Jin*_*won 5

选择Content-LengthTransfer-Encoding只是那些容器选择.这实际上是缓冲区大小的问题.

一种可能的解决方案是提供一个SevletFilter缓冲所有那些编组字节并设置Content-Length标头值的方法.

看到这个页面.

@WebFilter
public class BufferFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException {

        final ByteArrayOutputStream buffer =
            new ByteArrayOutputStream();

        // prepare a new ServletResponseWrapper
        // which returns the buffer as its getOutputStream();

        chain.doFilter(...)

        // now you know how exactly big is your response.

        final byte[] responseBytes = buffer.toByteArray();
        response.setContentLength(responseBytes.length);
        response.getOutputStream().write(responseBytes);
        response.flush();
    }

    @Override
    public void destroy() {
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 最好缓冲到文件(以避免内存不足 - >如果需要返回大响应).但我在这里看到了你的观点. (2认同)

MGH*_*MGH 5

在扩展 ResourceConfig 的类中,您可以设置缓冲区大小。高于此大小的响应将被分块,低于此大小的响应将具有内容长度。

public class ApplicationConfig extends ResourceConfig {

  public ApplicationConfig() {
    //your initialization
    property(CommonProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 2000000); 
  }
}
Run Code Online (Sandbox Code Playgroud)