springboot的get请求传入特殊符号报400错误(RFC 7230 and RFC 3986)

一、错误日志

2021-01-05 10:54:08.671 [http-nio-19000-exec-2] INFO  org.apache.coyote.http11.Http11Processor - Error parsing HTTP request header
 Note: further occurrences of HTTP request 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.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:468)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:260)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

二、源码分析

在org.apache.tomcat.util.http.parser中源码

static {
    for (int i = 0; i < ARRAY_SIZE; i++) {
    // Control> 0-31, 127
    if (i < 32 || i == 127) {
    IS_CONTROL[i] = true;
    }
    
    // Separator
    if (    i == '(' || i == ')' || i == '<' || i == '>'  || i == '@'  ||
    i == ',' || i == ';' || i == ':' || i == '\\' || i == '\"' ||
    i == '/' || i == '[' || i == ']' || i == '?'  || i == '='  ||
    i == '{' || i == '}' || i == ' ' || i == '\t') {
    IS_SEPARATOR[i] = true;
    }
    
    // Token: Anything 0-127 that is not a control and not a separator
    if (!IS_CONTROL[i] && !IS_SEPARATOR[i] && i < 128) {
    IS_TOKEN[i] = true;
    }
    
    // Hex: 0-9, a-f, A-F
    if ((i >= '0' && i <='9') || (i >= 'a' && i <= 'f') || (i >= 'A' && i <= 'F')) {
    IS_HEX[i] = true;
    }
    
    // Not valid for HTTP protocol
    // "HTTP/" DIGIT "." DIGIT
    if (i == 'H' || i == 'T' || i == 'P' || i == '/' || i == '.' || (i >= '0' && i <= '9')) {
    IS_HTTP_PROTOCOL[i] = true;
    }
    
    if (i >= '0' && i <= '9') {
    IS_NUMERIC[i] = true;
    }
    
    if (i >= 'a' && i <= 'z' || i >= 'A' && i <= 'Z') {
    IS_ALPHA[i] = true;
    }
    
    if (IS_ALPHA[i] || IS_NUMERIC[i] || i == '-' || i == '.' || i == '_' || i == '~') {
    IS_UNRESERVED[i] = true;
    }
    
    if (i == '!' || i == '$' || i == '&' || i == '\'' || i == '(' || i == ')' || i == '*' ||
    i == '+' || i == ',' || i == ';' || i == '=') {
    IS_SUBDELIM[i] = true;
    }
    
    // userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
    if (IS_UNRESERVED[i] || i == '%' || IS_SUBDELIM[i] || i == ':') {
    IS_USERINFO[i] = true;
    }
    
    // The characters that are normally not permitted for which the
    // restrictions may be relaxed when used in the path and/or query
    // string
    if (i == '\"' || i == '<' || i == '>' || i == '[' || i == '\\' || i == ']' ||
    i == '^' || i == '`'  || i == '{' || i == '|' || i == '}') {
    IS_RELAXABLE[i] = true;
    }
    }
    
    DEFAULT = new HttpParser(null, null);
}

public HttpParser(String relaxedPathChars, String relaxedQueryChars) {
    for (int i = 0; i < ARRAY_SIZE; i++) {
    // 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 == ' ' || i == '\"' || i == '#' || i == '<' || i == '>' || i == '\\' ||
    i == '^' || i == '`'  || i == '{' || i == '|' || i == '}') {
    IS_NOT_REQUEST_TARGET[i] = true;
    }

    /*
     * absolute-path  = 1*( "/" segment )
     * segment        = *pchar
     * pchar          = unreserved / pct-encoded / sub-delims / ":" / "@"
     *
     * Note pchar allows everything userinfo allows plus "@"
     */
    if (IS_USERINFO[i] || i == '@' || i == '/') {
    IS_ABSOLUTEPATH_RELAXED[i] = true;
    }

    /*
     * query          = *( pchar / "/" / "?" )
     *
     * Note query allows everything absolute-path allows plus "?"
     */
    if (IS_ABSOLUTEPATH_RELAXED[i] || i == '?') {
    IS_QUERY_RELAXED[i] = true;
    }
    }

    relax(IS_ABSOLUTEPATH_RELAXED, relaxedPathChars);
    relax(IS_QUERY_RELAXED, relaxedQueryChars);
}

三、解决办法

  1. 方法一:此方法在低版本tomacat中才适用
    在tomcat的catalina.properties中,找到最后注释掉的一行 #
    添加或者修改:
    tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}
    选项是按照字符分隔为一个数组,表示放行["|","{","}"]
    如果为中文则就不行。如果有?和&这些符合那么
    tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}?&
    除了上面配置,或者在最后一行添加:
    org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
  2. 方法二:(不推荐)
    更换tomcat版本。此方法比较快。
  3. 方法三:
    对相应的参数进行编码,就是将所有的参数都进行编码
  4. 方法四:
    选择另外的参数传递方法,比如post或者localStorage。
  5. 方法五:springboot内置版
    在启动时候添加tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}
    java -jar -Dtomcat.util.http.parser.HttpParser.requestTargetAllow=|{} demo-0.0.1-SNAPSHOT.jar

参考:https://stackoverflow.com/questions/41053653/tomcat-8-is-not-able-to-handle-get-request-with-in-query-parameters
relaxedQueryChars推荐使用
requestTargetAllow在tomcat8.5已弃用

四、最终配置

最终我在springboot中使用如下配置

import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class TomcatConfig {
    @Bean
    public TomcatServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addConnectorCustomizers((Connector connector) -> {
            connector.setProperty("relaxedPathChars", "\"<>[\\]^`{|}");
            connector.setProperty("relaxedQueryChars", "\"<>[\\]^`{|}");
        });
        return factory;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容