java 如何在没有传输编码的情况下发送 HTTP 响应:分块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16532728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I send an HTTP response without Transfer Encoding: chunked?
提问by Adam
I have a Java Servlet that responds to the Twilio API. It appears that Twilio does not support the chunked transfer that my responses are using. How can I avoid using Transfer-Encoding: chunked
?
我有一个响应 Twilio API 的 Java Servlet。Twilio 似乎不支持我的响应使用的分块传输。我怎样才能避免使用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 容器。
回答by cmbaxter
I believe that Jetty will use chunked responses when it doesn't know the response content length and/or it is using persistent connections. 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.
我相信当 Jetty 不知道响应内容长度和/或它使用持久连接时,它将使用分块响应。为了避免分块,您需要设置响应内容长度或通过在响应上设置 "Connection":"close" 标头来避免持久连接。
回答by Anthony Accioly
Try setting the Content-lengthbefore writing to the stream. Don't forget to calculate the amount of bytes according to the correct encoding, e.g.:
在写入流之前尝试设置Content-length。不要忘记根据正确的编码计算字节数,例如:
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);
回答by Popeye
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
. If the size of the data is larger than the HttpServletResponse.getBufferSize()
, then the response will be trunked. If not, Content-Length
will be used.
容器将根据使用Writer
或写入的数据大小自行决定使用 Content-Length 或 Transfer-Encoding outputStream
。如果数据的大小大于HttpServletResponse.getBufferSize()
,则响应将被中继。如果没有,Content-Length
将被使用。
In your case, just remove the 2nd flushing code will solve your problem.
在您的情况下,只需删除第二个刷新代码即可解决您的问题。