URI 中的斜杠 (/) 给出来自 Tomcat 的 HTTP 400 错误请求错误

Slash(/) in URI gives HTTP 400 Bad request error from Tomcat

我正在使用 Tomcat 7.0.54.0.

我的应用程序中有一个 REST API 使用 GET 方法。在这个 API 的 URI 中,有一个斜杠字符 (/),我在调用 API 之前对其进行了编码。那个例子:http://192.168.168.168:38080/myApp/getDetails/test%2Fstring.

URI 参数中的实际字符串是test/string。在调用 API 之前,我使用 URLEncoder.encode("test/string", "UTF-8"),这给了我 test%2Fstring。与我在 URL.

中使用的相同

这个 API 调用在一个环境中工作正常,但在其他环境中它给我一个 HTTP 400 (Bad request) 错误。

Java版本,Tomcat版本,OS环境(Linux)和版本,两个服务器都是一样的。在 server.xml 中,我这样配置连接器端口:

<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="38080" protocol="HTTP/1.1" redirectPort="8443"/>

另外,还有一个字符编码过滤器,配置如下代码:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
    HttpServletRequest httpRequest = null;
    HttpServletResponse httpResponse = null;

    if (request instanceof HttpServletRequest)
    {
        httpRequest = (HttpServletRequest) request;
    }

    if (response instanceof HttpServletResponse)
    {
        httpResponse = (HttpServletResponse) response;
    }

    // it means its not http request
    if (httpRequest == null || httpResponse == null)
    {
        chain.doFilter(request, response);
        return;
    }

    httpRequest.setCharacterEncoding("UTF-8");
    httpResponse.setCharacterEncoding("UTF-8");
    chain.doFilter(request, response);
}

当我调试时,我发现请求甚至没有到达这个过滤器。这意味着服务器本身正在限制 URL.

这个API以前工作得很好,但最近开始出现这个问题。唯一的区别是我拿了一个相同版本的新 Tomcat,并按照与现有 Tomcat.

完全相同的方式配置它

任何人都可以解释发生了什么以及如何解决它吗?

我解决了这个问题。我需要在 JAVA_OPTS.

中设置 -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true-Dorg.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH=true

详情请参考以下内容:

Configuring Tomcat for encoded slashes in the URL