println it

Software blog about tools, builds and making it all work

Say “No” to ServletResponse.setContentLength()




javax.servlet.ServletResponse.setContentLength(int) is a new kind of Y2k bug. It accepts int assuming no files larger than 2Gb will ever be sent as an HTTP response.

If you pass a long larger than 231-1 which is exactly 2Gb, it overflows and negative header is sent in response.

Free Download Manager fails to download a file and Apache Commons HttpClient v3.1 downloads an empty one (need to check version 4)

Too bad Java SE did the same mistake and java.net.URLConnection.getContentLength() returns int as well, it means the API will never be changed.

Right now the solution is to use HttpServletResponse.setHeader(String,String):

long length = file.length();
..
response.setHeader( "Content-Length", String.valueOf( length ))

Other APIs have taken the right route though:

One Response to “Say “No” to ServletResponse.setContentLength()”

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>