In WebFlux-WebFilter, how can I identify whether an inbound HTTP request has a body or not?

596 Views Asked by At

In WebFilter, how can I identify whether an inbound HTTP request has a body or not? I am aware of the Content-Length header presence check, but it's a hack at the best. Besides, it will not catch all the cases (some of the clients are sending the body without the Content-Length header).

Note: I just need to identify whether the body is there or not, reading body is a whole different question!

The server is Netty, if that helps.

1

There are 1 best solutions below

2
Pelle Nilsen On

In WebFlux you can use the 'HttpMessageReader' interface to determine whether an inbound HTTP request has a body or not. This interface is used to read the body of a request, so you can check if there is a registered 'HttpMessageReader' that supports the 'Content-Type' of the request.

If there is such a reader, then the request has a body; if not, then the request doesn't have a body.

Sample code:

HttpMessageReader httpMessageReader = new HttpMessageReader();
if (httpMessageReader.canRead(MyRequestType.class, MediaType.APPLICATION_JSON)) {
    // if canRead returns true, there is a body
} else {
    // if canRead returns false, there is no body
}