tomcat---Request header is too large和Request Entity Too Large的正确解决方法

在平常开发中,tomcat应该是程序员接触最多的服务器。平常做文件上传容易碰到Request Entity Too Large异常,偶尔会碰到Request header is too large异常,大致看了下网上的解决方案,天下文章一大抄,还都抄错。这里给出正确解决方法。


Request Entity Too Large

从字面意思可知,是请求体过大,多见于文件上传时触发,设置connectormaxPostSize为大点的值即可,单位byte,默认值:2097152 (2 megabytes)。若想将其设为无限制,则将其设置为负数即可。网上解决方案大多说设置为0,这是错的,设置为0会导致tomcat截断post的参数,导致后台接收到的参数全都是null。官方文档原文如下:

maxPostSize :
The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than zero. If not specified, this attribute is set to 2097152 (2 megabytes).

链接如下:
http://tomcat.apache.org/tomcat-9.0-doc/config/http.html#Common_Attributes
注意,官方文档说的是less than zero,也就是说设置为小于0的值才是设置maxPostSize为无限制,网上的大多数解决方法说的设置为0是错的。
示例如下:

<!--设置maxPostSize限制为200MB-->
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" 
    maxPostSize="209715200"/>

Request header is too large

从字面意思可知,是请求头过大,设置connectormaxHttpHeaderSize为大点的值即可,单位byte,默认值:8192 (8 KB)。官方文档原文如下:

maxHttpHeaderSize :
The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 8192 (8 KB).

链接如下:
http://tomcat.apache.org/tomcat-9.0-doc/config/http.html#Standard_Implementation
注意,官方文档并没有说明如何将该值设置为无限制,所以尽量不要将其设置为负数以免程序出错。
示例如下:

<!--设置maxHttpHeaderSize限制为16KB,可根据需求适当加到更大-->
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" 
    maxHttpHeaderSize="16384"/>

注意:该值设置过大,容易造成内存溢出的问题,切记切记。


综上,避免 Request header is too large和Request Entity Too Large的最好的配置就是同时配置俩属性为较大的值,避免不必要的麻烦。示例如下:

<!--设置maxPostSize限制为200MB,设置maxHttpHeaderSize限制为16KB-->
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" 
    maxPostSize="209715200" maxHttpHeaderSize="16384"/>

原创不易,转帖请注明出处——–shizhongqi


猜你喜欢

转载自blog.csdn.net/lianjunzongsiling/article/details/79902938