java.lang.IllegalArgumentException: Invalid character found in the request target.

最近在使用 Spring Boot 开发项目的时候遇到了这样一个错误:

java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986

请求中包含无效字符,有效字符的定义请查看 RFC 7230 和 RFC 3986。

查看了一下我的请求参数,应该是 [] 字符被 Tomcat 当作无效字符处理了。

Request Params:
expressNumber[]=111&expressNumber[]=222&expressNumber[]=333

在网上找了一下解决方案,需要在 Tomcat 配置文件中添加 relaxedQueryChars。

Tomcat >= 8.5
relaxedQueryChars = "[]"

由于 Spring Boot 使用的是 Embedded Tomcat ,可以参考以下设置方式。

@Component
public class MyTomcatWebServerCustomizer
        implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        factory.addConnectorCustomizers(connector -> connector.setAttribute("relaxedQueryChars", "[]"));
    }
}

问题已经成功解决了,但是还有另外一种思路。

再来看一下我的请求参数,是要传递一个数组。

Request Params:
expressNumber[]=111&expressNumber[]=222&expressNumber[]=333

Java Code:
@RequestParam(name = "expressNumber[]") String[] expressNumber

有没有其他方式呢?有的,而且还有两种。

Request Params:
expressNumber=111&expressNumber=222&expressNumber=333

Java Code:
@RequestParam String[] expressNumber
Request Params:
expressNumber=111,222,333

Java Code:
@RequestParam String[] expressNumber

参考:

https://stackoverflow.com/questions/48655291/java-lang-illegalargumentexception-invalid-character-found-in-the-request-targe

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

https://stackoverflow.com/questions/51703746/setting-relaxedquerychars-for-embedded-tomcat

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-web-servers.html

 1,831 total views