RSS
 

Say “No” to ServletResponse.setContentLength()

05 Aug



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:

 
1 Comment

Posted in Spring, Web

 

Leave a Reply

 

 
  1. Evgeny Goldin

    August 5, 2010 at 3:25 PM

    From Apache HTTP client Javadoc: “If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned” – they took it really seriously