Spring MVC – measure length of incoming requests of type x-www-form-urlencoded

I’m using Spring Boot 2.7.18 and Spring MVC.
I made a OncePerRequestFilter that counts the bytes passing through the InputStream of each request, by “hijacking” the original InputStream and replacing it with an implementation that does the counting as the stream is being read from.

The problem is that this doesn’t work with requests with Content-Type application/x-www-form-urlencoded because both Tomcat’s and Undertow’s implementations of the HttpServletRequest interface use their own internal instance of the InputStream to read the parameters of such type of requests, thus bypassing my solution.

I don’t want to re-implement the getParameterValues method because it would surely be much less secure and thorough than Tomcat’s and Undertow’s, and copy-pasting one of their implementations in my code is also a no-no…

How can I get around this issue? Does Spring provide some way to read a request’s length more easily? I can’t rely on the Content-Length header because I have no guarantee that it’s going to be set by the caller.

Important note: I do NOT only need to log the request body’s length. The code below is just pseudo-code. I need to obtain the length of the request to do stuff with it, so please don’t recommend me libraries that are only used to log the request’s data (I saw there are at least a couple). Thank you.

Here’s what I did so far:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.FilterChain;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

public class RequestBodyMeasuringFilter extends OncePerRequestFilter {
    
    private final Logger log = LoggerFactory.getLogger(RequestBodyMeasuringFilter.class);
    
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        
        HttpServletRequest requestToUse;
        boolean isFormRequest = MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(MediaType.parseMediaType(request.getContentType()));
        if (!request.getMethod().equals(HttpMethod.POST.toString()) && !request.getMethod().equals(HttpMethod.PUT.toString())
                || isFormRequest) {
            if (isFormRequest)// falling back on the Content-Length header that isn't guaranteed to be present...
                log.info("Request length: {}", request.getContentLength());
            requestToUse = request;
        } else {
            requestToUse = new BodyMeasuringHttpServletRequestWrapper(request, value);
        }
        chain.doFilter(requestToUse, response);
    }

    private static class BytesCountingServletInputStream extends ServletInputStream {

        private final AtomicInteger size = new AtomicInteger(0);
        private final InputStream inputStream;

        public BytesCountingServletInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        public int getSize() {
            return this.size.get();
        }

        @Override
        public boolean isFinished() {
            try {
                return inputStream.available() == 0;
            } catch (IOException ex) {
                log.error("Error in isFinished", ex);
            }
            return false;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
            throw new UnsupportedOperationException();
        }

        @Override
        public int read() throws IOException {
            int r = this.inputStream.read();
            if (r != -1) {
                this.size.incrementAndGet();
            } else {
                // if r == -1 it means we reached the end of the stream.
                // during tests I saw I can't rely on the "close" method...
                log.info("Request length: {}", getSize());
            }
            return r;
        }
    }

    public static class BodyMeasuringHttpServletRequestWrapper extends HttpServletRequestWrapper {

        private BytesCountingServletInputStream inputStream;

        public BodyMeasuringHttpServletRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        @Override
        public int getContentLength() {
            return inputStream.getSize();
        }

        @Override
        public ServletInputStream getInputStream() {
            replaceOriginalInputStream();
            return inputStream;
        }

        @Override
        public BufferedReader getReader() {
            replaceOriginalInputStream();
            return new BufferedReader(new InputStreamReader(inputStream));
        }

        private void replaceOriginalInputStream() {
            try {
                if (inputStream == null)
                    inputStream = new BytesCountingServletInputStream(super.getInputStream());
            } catch (IOException ex) {
                throw new RuntimeException("Error when trying to obtain the request's InputStream.", ex);
            }
        }
    }
}

Again, this above is pseudo-code… well, not so pseudo, it does work but I’ve left out my own business logic where I extract the measured body length and use it for other stuff.
If you remove the isFormRequest boolean in order to treat x-www-form-urlencoded POST/PUT requests like the others, you will see that the request length won’t be logged, with these.

Thank you for any help.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật