公司tomcat從8.0.22更換到高版本的9.0.22以后,postman請求沒問題,但是終端請求總是400
報Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986錯,
原因:
RFC 3986規范定義了Url中只允許包含英文字母(a-zA-Z)、數字(0-9)、-_.~4個特殊字符以及所有保留字符(RFC3986中指定了以下字符為保留字符:! * ’ ( ) ; : @ & = + $ , / ? # [ ])。而我們的系統在通過地址傳參時,在url中傳了一段json,傳入的參數中有”{“不在RFC3986中的保留字段中,所以會報這個錯。
解決:
1、在tomcat的conf/server.xml 的Connector中添加:relaxedQueryChars="{}|[],%" relaxedPathChars="[]|{},%" 需要編碼什么特殊字符添加什么。
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000"
relaxedQueryChars="[]|{}^\`"<>
" relaxedPathChars="[]|{}^\`"<>
" redirectPort="8443" />
有中文的話加上:URIEncoding="UTF-8"。
HTML5轉義字符
numeric character reference(NCR),數字取值為目標字符的 Unicode code point;以「&#」開頭的后接十進制數字,以「&#x」開頭的后接十六進制數字。
https://dev.w3.org/html5/html-author/charref
2、請求前編碼:URLEncoder.encode(param)