当数据存在时,http响应使用分块编码

时间:2013-03-18 21:15:06

标签: java google-app-engine http networking

我有一个Web服务,当被调用时,可能会或可能不会发回一个带有响应的正文。出于某种原因,只要没有数据,Content-Length标头就会出现,但是当我发回一个主体时,会出现Transfer-Encoding:Chunked标头而不是Content-Length标头。事实上,发送的请求是分块的,但我不一定需要响应,因为我们希望有效负载尽可能小。

如下面的代码所示,我尝试在发回数据时强制内容长度,但即便如此,响应仍然没有Content-Length头。我已经读过Transfer-Encoding:Chunked标头的存在将覆盖任何COntent-Length标头,但我无法弄清楚如何删除Transfer-Encoding标头,或者甚至为什么它首先出现在那里

以下是我对新请求的回调:

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    resp.setStatus(200);

    String mac = req.getHeader("x-kcid");
    String cmd = getCache(mac);

    if (cmd != null) {
        writeToStream(resp, cmd, "text/plain");
        clearCache(mac);
    }
}

以下是实际写入响应的方法:

private static void writeToStream(HttpServletResponse resp, String msg, String contentType) throws IOException {        
    resp.setContentType(contentType);
    resp.setContentLength(msg.getBytes().length);
    resp.getWriter().write(msg);
}

1 个答案:

答案 0 :(得分:2)

GAE doesn't allow设置Transfer-EncodingContent-Length标头。 (那些标题,以及其他一些标题被忽略并从响应中移除)。