[英]How do I send an HTTP response without Transfer Encoding: chunked?
I have a Java Servlet that responds to the Twilio API. 我有一个响应Twilio API的Java Servlet。 It appears that Twilio does not support the chunked transfer that my responses are using. 似乎Twilio不支持我的回复使用的分块转移。 How can I avoid using Transfer-Encoding: chunked
? 如何避免使用Transfer-Encoding: chunked
?
Here is my code: 这是我的代码:
// response is HttpServletResponse
// xml is a String with XML in it
response.getWriter().write(xml);
response.getWriter().flush();
I am using Jetty as the Servlet container. 我使用Jetty作为Servlet容器。
I believe that Jetty will use chunked responses when it doesn't know the response content length and/or it is using persistent connections. 我相信当Jetty不知道响应内容长度和/或使用持久连接时,它将使用分块响应。 To avoid chunking you either need to set the response content length or to avoid persistent connections by setting "Connection":"close" header on the response. 要避免分块,您需要设置响应内容长度或通过在响应上设置“连接”:“关闭”标头来避免持久连接。
Try setting the Content-length before writing to the stream. 尝试在写入流之前设置Content-length 。 Don't forget to calculate the amount of bytes according to the correct encoding, eg: 不要忘记根据正确的编码计算字节数,例如:
final byte[] content = xml.getBytes("UTF-8");
response.setContentLength(content.length);
response.setContentType("text/xml"); // or "text/xml; charset=UTF-8"
response.setCharacterEncoding("UTF-8");
final OutputStream out = response.getOutputStream();
out.write(content);
The container will decide itself to use Content-Length or Transfer-Encoding basing on the size of data to be written by using Writer
or outputStream
. 容器将根据要使用Writer
或outputStream
写入的数据大小决定使用Content-Length或Transfer-Encoding。 If the size of the data is larger than the HttpServletResponse.getBufferSize()
, then the response will be trunked. 如果数据的大小大于HttpServletResponse.getBufferSize()
,则响应将被中继。 If not, Content-Length
will be used. 如果不是,将使用Content-Length
。
In your case, just remove the 2nd flushing code will solve your problem. 在您的情况下,只需删除第二个刷新代码将解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.