ServletResponse 的 setContentLength() 方法实际上做了什么?

What does setContentLength() method of ServletResponse actually do?

根据文档,ServletResponse 接口的 setContentLength(int len) 方法设置响应中内容的长度 body 在 HTTP servlet 中,此方法设置 HTTP Content-Length header.

这是 class 的 doGet() 方法的扩展 HttpServlet:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/plain");
    response.setContentLength(6);
    PrintWriter out = response.getWriter();
    out.write("What's your name? ");
    out.write("" + response.isCommitted());
}

当我在 Chrome 浏览器上 运行 时,输出是:What's your name? false

我很困惑这里计算setContentLength()长度的度量到底是什么,是字节、字符还是什么,如果它设置了[=36=的内容长度],为什么 response.isCommitted() returns false 和我想输出的文本的长度不是 t运行 不知何故?谢谢。

I am confusing what actually is the metric for calculating the length of the setContentLength() here, whether it is in byte, character, or something

它在 byte.

查看 this or Section#14.13 Content-Length of the specification 了解详情。

When I run this on the Chrome browser, the output is: What's your name? false

我怀疑你所说的真实性。

下面是我的 Chrome 浏览器的截图:

下面是我的火狐浏览器截图: