springspring-mvcheadcontent-lengthhttp-content-length

How to stop Spring MVC from automatically adding the "Content-Length: 0" header to HEAD responses?


I'm specifically trying to test the case where my application doesn't receive a Content-Length header from the server, so I've set up my code not to include that header, but for some reason Spring is including it anyway with a value of 0:

@RequestMapping(value = "/test", method = RequestMethod.HEAD)
public void headTest(HttpServletRequest request, HttpServletResponse response) {
    response.addDateHeader("Date", System.currentTimeMillis());
    response.addHeader("Accept-Ranges", "bytes");
    response.addHeader("Content-Type", "video/mp4");
}
$ curl -I http://myserver.com:8600/test
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Date: Thu, 28 Jul 2022 01:05:11 GMT
Accept-Ranges: bytes
Content-Type: video/mp4
Content-Length: 0

How can I stop Spring from including this header?


Solution

  • Setting a header to null to effectively remove it from the response works for embedded Tomcat and might work for other servers:

    response.setHeader("Content-Length", null);