如何检测 HttpServletRequest 是否有主体?

How to detect if HttpServletRequest has body?

我正在尝试检测一个 http 请求是否有正文而不读取它或做任何使现有代码无法处理它的任何事情,无论它在流程的后面做什么。

boolean hasBody(HttpServletRequest http) {
    boolean hasBody = false;
    try {
        hasBody = http.getInputStream() != null; // always gives true
        hasBody = http.getReader().ready(); // always gives IllegalStateException
    } catch (IOException e) {
    }
    return hasBody;
}

不幸的是,当我将它们作为 GET 和 POST 与正文进行测试时,我想出的两个检查都不起作用。

注意,我不想这样做:"POST".equals(http.getMethod())!"GET".equals(http.getMethod()) 如果可能,因为我不确定有或没有 body 的方法。

您可以使用 getContentLength() 或 getContentLengthLong() 并检查它是否为正值。

包含 body 的请求如果遵循 https://www.rfc-editor.org/rfc/rfc7230#section-3.3

则应设置特定的 headers

The presence of a message body in a request is signaled by a Content-Length or Transfer-Encoding header field.

您可以使用 http.getHeader("transfer-encoding") != null || http.getHeader("content-length") != null 检查这些 header 是否存在。

请求 body 可能存在但为空。如果你想知道你可以添加一个内容长度> 0 的检查,但这只有在请求包含内容长度 header 时才有效。看起来你必须尝试读取请求 body 以查看在没有内容长度 header.

时是否为空