Jersey / JAX-RS:在响应头而不是分块传输编码中返回Content-Length [英] Jersey/JAX-RS : Return Content-Length in response header instead of chunked transfer encoding
问题描述
我正在使用Jersey创建RESTful API资源,并使用 ResponseBuilder
来生成响应。
I'm using Jersey to create RESTful API resources, and ResponseBuilder
to generate the response.
示例RESTful资源的代码:
Example code for the RESTful resource:
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();
}
}
在响应中,它返回了分块传输编码响应标头。 泽西世界中的正确方法是让它返回 Content-Length
标题,而不是 Transfer-Encoding:chunked $回复标题中的c $ c>标题?
In the response, it's returning chunked transfer encoding in the response headers. What is the proper way in the "Jersey world" to have it return the Content-Length
header instead of the Transfer-Encoding: chunked
header in the response headers?
推荐答案
选择 Content-Length
或 Transfer-Encoding
只是那些容器选择。这实际上是缓冲区大小的问题。
Selecting Content-Length
or Transfer-Encoding
is just those Containers choice. It's really a matter of buffer size.
一种可能的解决方案是提供一个 SevletFilter
,它可以缓冲所有那些编组的字节和设置 Content-Length
标头值。
One possible solution is providing a SevletFilter
which buffers all those marshalled bytes and sets Content-Length
header value.
参见此页。
@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() {
}
}
这篇关于Jersey / JAX-RS:在响应头而不是分块传输编码中返回Content-Length的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!