我正在使用 Tomcat 7.0.54.0。
我的应用程序中有一个使用 GET
方法的 REST API。在这个 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(错误请求)
错误。
Java版本、Tomcat版本、操作系统环境(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 完全相同的方式进行配置。
谁能解释发生了什么以及如何解决它?
最佳答案
我解决了这个问题。我需要设置 -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
和 -Dorg.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH=true
在我的 JAVA_OPTS
中。
详情请引用以下内容:
关于tomcat - URI 中的斜杠 (/) 给出来自 Tomcat 的 HTTP 400 错误请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52752829/