java javax.servlet.HttpServletRequest.getContentLength() 只返回 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7423285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javax.servlet.HttpServletRequest.getContentLength() returns int only
提问by Hank
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.
为了处理 HTTP POST 或 PUT 中的大型请求主体,依赖HttpServletRequest.getContentLength()
并不是一个好主意,因为它只返回整数值,或者 -1 表示请求主体 > 2GB。
However, I see no reason, why larger request bodies should not be allowed. RFC 2616 says
但是,我看不出为什么不允许更大的请求主体。RFC 2616 说
Any Content-Length greater than or equal to zero is a valid value.
任何大于或等于零的 Content-Length 都是有效值。
Is it valid to use HttpServletRequest.getHeader('content-length')
and parse it to Long instead?
使用HttpServletRequest.getHeader('content-length')
并将其解析为 Long是否有效?
采纳答案by Bozho
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.
是的,这是一个很好的方法 - 使用getHeader("Content-Length")
(大写)和Long.parseLong(..)
. 我相信这是容器正在做的事情,但它受到int
serlvet 规范的限制。
回答by BalusC
Since Servlet 3.1 (Java EE 7), a new method is available, getContentLengthLong()
:
从 Servlet 3.1 (Java EE 7) 开始,提供了一种新方法getContentLengthLong()
:
long contentLength = request.getContentLengthLong();
The same applies to its counterpart on the response, setContentLengthLong()
:
这同样适用于响应中的对应项setContentLengthLong()
:
response.setContentLengthLong(file.length());