'What's the most reliable way to limit HTTP body size? [duplicate]

I'd like to limit the allowed length of the bodies of incoming HTTP POST requests in my Spring-based Java server application. Most of these requests contain payloads with content type application/json. However, some of them have other content types, e.g. some controllers receive application/octet-stream from a messaging service.

So far, I had been working with a javax.servlet.Filter, that inspects the content length and rejects any overlong requests:

@Component
@WebFilter(urlPatterns = "my-path/*")
public class Limiter implements Filter {

    private static final int MAX_CONTENT_LENGTH_IN_BYTES = 5000;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        int length = servletRequest.getContentLength();
        if (length > MAX_CONTENT_LENGTH_IN_BYTES) {
            // reject request with HTTP 400 Bad Request
        } else {
            // let the request pass
        }

}

While this works fine for JSON-based contents, it fails for some of the others, esp. the octet-streams. For these cases, getContentLength() consistently returns -1. From the Java documentation, I gather that this indicates that the length is unavailable from the input stream.

What's a more reliable way to inspect the content length? Clone the stream, then retrieve it as a string and check the string's length?

Given the first answers, and the redirection to Increase HTTP Post maxPostSize in Spring Boot, let me add this: Don't the multipart settings only affect multipart HTTP requests, i.e. the ones that are split into several chunks for better data transfer? What if my request is big but arrives in a single part?



Solution 1:[1]

This may be done directly in the configuration file of your Spring application, e.g in application.yml .

The following would limit sizes to 1Gb.

spring:
  http:
    multipart:
      max-file-size: 1000MB
      max-request-size: 1000MB

Solution 2:[2]

You can use Tomcat's settings to do that

spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=1MB

That is obivously for embedded Tomcat if you are using SpringBoot. Otherwise you will have to do such configuration on connector settings which can be found in Tomcat documentation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arnaud
Solution 2 Antoniossss