2
votes

I have a web service that, when called, may or may not send a body back with the response. For some reason, whenever there is no data the Content-Length header is present, but when I send back a body, a Transfer-Encoding: Chunked header is present instead of the Content-Length header. The request being sent up is, in fact, chunked, but i don't necessarily need the response to be as we want the payload to be a small as possible.

As the following code illustrates, I have tried forcing the content length when data is sent back, but even so, the response still does not have a Content-Length header. I have read that the existence of a Transfer-Encoding: Chunked header will override any COntent-Length header, but I can't figure out how to remove the Transfer-Encoding header, or even why it is there in the first place.

Here is the my callback for a new request:

@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);
    }
}

and here is the method that actually writes the response:

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

1 Answers

2
votes

GAE doesn't allow setting the Transfer-Encoding or Content-Length header. (That headers, and some others are ignored and removed from the response).