Invalid character found in the request target. The valid characters are defined in RFC 7230 and RF

末蓝、 2023-07-21 15:28 97阅读 0赞

环境说明

在做javaweb项目的时候,涉及到了文件下载,由于我要下载的文件中,各种标题的都有,导致一点击下载,就会报错。查询日志发现是有些URL请求被tomcat认为存在不合法字符,错误信息如下:

  1. Invalid character found in the request target.The valid characters are defined in RFC 7230 and RFC3986

在这里插入图片描述
我当时的Tomcat用的7.0.99版本

原因

经了解,这个问题是高版本tomcat中的新特性:就是严格按照 RFC 3986规范进行访问解析,而 RFC 3986规范定义了Url中只允许包含英文字母(a-zA-Z)、数字(0-9)、-_.~4个特殊字符以及所有保留字符(RFC3986中指定了以下字符为保留字符:! * ’ ( ) ; : @ & = + $ , / ? # [ ])。而我们的系统在通过地址传参时,在url中传了一段json,传入的参数中有”{“不在RFC3986中的保留字段中,所以会报这个错。

根据(https://bz.apache.org/bugzilla/show\_bug.cgi?id=60594) ,从以下版本开始,有配置项能够关闭/配置这个行为:
8.5.x系列的:8.5.12 onwards
8.0.x系列的:8.0.42 onwards
7.0.x系列的:7.0.76 onwards

具体来说:

org.apache.tomcat.util.http.parser.HttpParser#IS_NOT_REQUEST_TARGET[]中定义了一堆not request target
if(IS_CONTROL[i] || i > 127 || i == 32 || i == 34 || i == 35 || i == 60 || i == 62 || i == 92 || i == 94 || i == 96 || i == 123 || i == 124 || i == 125) { IS_NOT_REQUEST_TARGET[i] = true; }

解决办法

方法1

…/conf/catalina.properties中,找到最后注释掉的一行 #tomcat.util.http.parser.HttpParser.requestTargetAllow=| ,改成tomcat.util.http.parser.HttpParser.requestTargetAllow=|{},然后去掉这句话的注释。

在这里插入图片描述

这种方法只适合对应的应为,如果为中文则就不行。如果有?和&这些符合那么tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}?&

补充

按照上面的方法处理好后,在非IE浏览器上访问,是没有问题了。但若是在IE浏览器上进行访问,这个错误还是会出现,在IE上访问出现这个错误的原因:因为url的参数json中有双引号,火狐和谷歌浏览器会自动对url进行转码,但IE不会

这种情况的处理方法:
给系统配置方向代理服务器,通过反向代理服务器进行urlrewrite,手动取出各个json的数据,手动将双引号进行转码为%22:

具体方式如下:
编辑 Apache安装目录/conf/httpd.conf, 在配置MAS反向代理的前面添加如下信息:

  1. RewriteCond %{QUERY_STRING} json
  2. RewriteCond %{QUERY_STRING} !msKey
  3. RewriteCond %{QUERY_STRING} msInfo
  4. RewriteCond %{QUERY_STRING} player
  5. RewriteCond %{QUERY_STRING} {^a-zA-Z0-9[^a-zA-Z0-9]:^a-zA-Z0-9[^a-zA-Z0-9],^a-zA-Z0-9[^a-zA-Z0-9]:^a-zA-Z0-9[^a-zA-Z0-9]}
  6. RewriteRule ^(.*)? $1?method=sendJson&json={%22%1%22:%22%2%22,%22%3%22:%22%4%22} [R,L,NE]

方法2:

最轻便的方法,更换tomcat版本。此方法比较快。我将Tomcat版本改为了7.0.70

方法3:

对相应的参数进行编码,就是将所有的参数都进行编码

方法4:

选择另外的参数传递方法,比如post或者localStorage。

可以直接下载对应的版本的tomcat

http://archive.apache.org/dist/tomcat/tomcat-6/

http://archive.apache.org/dist/tomcat/tomcat-7/

http://archive.apache.org/dist/tomcat/tomcat-8/

http://archive.apache.org/dist/tomcat/tomcat-9/

参考

https://stackoverflow.com/questions/41053653/tomcat-8-is-not-able-to-handle-get-request-with-in-query-parameters

https://www.cnblogs.com/lr393993507/p/7755867.html

https://www.cnblogs.com/wsygdb/p/7661220.html

https://tomcat.apache.org/tomcat-7.0-doc/config/systemprops.html(官网各配置项说明)

发表评论

表情:
评论列表 (有 0 条评论,97人围观)

还没有评论,来说两句吧...

相关阅读