Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required request body is missing after using ContentCachingRequestWrapper

I need to read the request payload in one of my GenericFilterBean. Beacuse I cannot call getreader twice I used ContentCachingRequestWrapper like-

HttpServletRequest httpRequest = (HttpServletRequest) request;
ContentCachingRequestWrapper cachedRequest = new ContentCachingRequestWrapper(httpRequest);

Getting the request body-

String payload = cachedRequest.getReader().lines().collect(Collectors.joining());

And chaining the request-

chain.doFilter(cachedRequest, response);

But still my controller throws-

 .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<?> com.siemens.plm.it.sf.api.controllers.OrderController.createCCOrder(com.siemens.plm.it.de.ms.provisioning.model.sap.SapQuoteCreationArgument,javax.servlet.http.HttpServletRequest) throws java.lang.Exception

How do I chain the request so I can read the payload in the controller as well?

like image 246
Itsik Mauyhas Avatar asked Jun 25 '26 04:06

Itsik Mauyhas


1 Answers

I faced same issue. You need to call getInputStream on requestWrapper in order to let it be cached. This is how your filter should look like:

@Component
public class CachingRequestBodyFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper((HttpServletRequest) servletRequest);

        //this line is necessary to cache InputStream
        wrappedRequest.getInputStream();
        //String requestBody = IOUtils.toString(wrappedRequest.getInputStream(), StandardCharsets.UTF_8); with this line you can map requestBody to String


        chain.doFilter(wrappedRequest, servletResponse);
    }
}

Controller:

@PostMapping(ENDPOINT)
    void endpoint(HttpServletRequest request) {
        ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) request;
        String requestBody = new String(requestWrapper.getContentAsByteArray());
        //process requestBody
}
like image 75
Krzysztof K Avatar answered Jun 26 '26 18:06

Krzysztof K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!