Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.servlet.HttpServletRequest.getContentLength() returns int only

Tags:

java

servlets

In order to deal with a large request body in a HTTP POST or PUT, relying on HttpServletRequest.getContentLength() is not a good idea, since it returns only integer values, or -1 for request bodies > 2GB.

However, I see no reason, why larger request bodies should not be allowed. RFC 2616 says

Any Content-Length greater than or equal to zero is a valid value.

Is it valid to use HttpServletRequest.getHeader('content-length') and parse it to Long instead?

like image 223
Hank Avatar asked Sep 14 '11 21:09

Hank


2 Answers

Since Servlet 3.1 (Java EE 7), a new method is available, getContentLengthLong():

long contentLength = request.getContentLengthLong();

The same applies to its counterpart on the response, setContentLengthLong():

response.setContentLengthLong(file.length());
like image 76
BalusC Avatar answered Nov 15 '22 20:11

BalusC


Yes, this is a fine approach - use getHeader("Content-Length") (capitalized) and Long.parseLong(..). I believe it's what the container is doing, but it is limited to int by the serlvet spec.

like image 10
Bozho Avatar answered Nov 15 '22 18:11

Bozho