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

在 Tomcat 高版本中,有增加对请求 URL 内容的严格控制,如果出现特殊字符,如:http://127.0.0.1:9999/demo1?1^1中的 ^ 就会抛出如下异常:

1
2
3
4
5
6
7
8
9
10
11
12
[20:02:26 513] [INFO]  Http11NioProcessor.process(1111): Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
at org.apache.coyote.http11.AbstractNioInputBuffer.parseRequestLine(AbstractNioInputBuffer.java:287)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1065)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

通过查看源码可以看出 Tomcat 有对诸如控制符、^、# 等的特殊字符做验证。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// org.apache.tomcat.util.http.parser.HttpParser.java

// Control> 0-31, 127
if (i < 32 || i == 127) {
IS_CONTROL[i] = true;
}

// Not valid for request target.
// Combination of multiple rules from RFC7230 and RFC 3986. Must be
// ASCII, no controls plus a few additional characters excluded
if (IS_CONTROL[i] || i > 127 ||
i == '' || i == '\\"' || i == '#' || i == '<' || i == '>' || i == '\\\\' ||
i == '^' || i == '`' || i == '{' || i == '|' || i == '}') {
if (!REQUEST_TARGET_ALLOW[i]) {
IS_NOT_REQUEST_TARGET[i] = true;
}
}

解决方法

1,对请求的 URL 做 HTMLEncode 转码。

2,更改请求方式,比如:GET 改成 POST,将请求参数放到请求包体中。

3,降级 Tomcat 版本(不推荐)。