Sobes.tech
Senior

How to solve the problem of re-reading the request body (InputStream is read only once)?

sobes.tech AI

Answer from AI

The problem of reading the request body multiple times in Java is related to the fact that InputStream can only be read once. To solve this problem, a wrapper is usually used that caches the request body, allowing it to be read multiple times.

For example, in servlets, you can create a class that extends HttpServletRequestWrapper, which saves the body in a buffer:

public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {
    private byte[] cachedBody;

    public CachedBodyHttpServletRequest(HttpServletRequest request) throws IOException {
        super(request);
        InputStream requestInputStream = request.getInputStream();
        this.cachedBody = requestInputStream.readAllBytes();
    }

    @Override
    public ServletInputStream getInputStream() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
        return new ServletInputStream() {
            @Override
            public int read() {
                return byteArrayInputStream.read();
            }
            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }
            @Override
            public boolean isReady() {
                return true;
            }
            @Override
            public void setReadListener(ReadListener listener) {}
        };
    }
}

Thus, the request body can be read multiple times from the cached byte array.

How to solve the problem of re-reading the request… - sobes.tech