Reputation: 19237
I am trying to detect if an http request has body without reading it or doing anything that makes it impossible for the existing code to do with it whatever it does later in the flow.
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;
}
Unfortunately both checks I could come up with don't work when I test them both as GET and as POST with body.
Note, I don't want to do: "POST".equals(http.getMethod())
or !"GET".equals(http.getMethod())
if possible, 'cause I'm not sure what methods there could be with or without body.
Upvotes: 1
Views: 2783
Reputation: 111259
A request that includes a body should have a certain headers set if it follows https://www.rfc-editor.org/rfc/rfc7230#section-3.3
The presence of a message body in a request is signaled by a Content-Length or Transfer-Encoding header field.
You can check the presence of these headers with http.getHeader("transfer-encoding") != null || http.getHeader("content-length") != null
.
The request body may be present but empty. If you want to catch that you could add a check for content length > 0, but that will only work if the request includes a content length header. It looks like you have to try to read the request body to see if it is empty when there is no content length header.
Upvotes: 1
Reputation: 339
You can use getContentLength() or getContentLengthLong() and check if it is positive.
Upvotes: 5