如何检测 HttpServletRequest 是否有 body?

Gav*_*iel 1 servlets

我正在尝试检测 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

And*_*lov 5

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