0

When ever I try to get the request body inside the springboot filter (in order to check some parameters) a BAD request error is thrown

Here's the code for the filter

public class PostURLFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        InputStream requestInputStream = req.getInputStream();
        try {
            String body = StreamUtils.copyToString(requestInputStream, StandardCharsets.UTF_8);
            out.println(body + "this is the body");


        } catch (Exception e) {
            out.println(e);
        }


        out.println("end");

        filterChain.doFilter(servletRequest, servletResponse);


    }
}

This is my POST request body

{
       "id":590,
       "name":"run"
}

Without this piece of code (requesting the request body) the POST request works fine. But with this it doesn't run.

I don't know where I'm missing the login. Kindly help me. Thanks in advance!

4EACH
  • 2,132
  • 4
  • 20
  • 28
Akil S
  • 21
  • 4
  • Did you try to debug? share your errors from log – 4EACH Jan 31 '23 at 07:19
  • Because you can only consume the body of the request once. You already consume it in the filter, there is nothing left for the controller to use and thus a bad request. You need to wrap your request in a `ContentCachingRequestWrapper` from that read the inputstream and pass the wrapped request along (instead of the original). – M. Deinum Jan 31 '23 at 08:28
  • @M.Deinum thanks buddy. I realised this issue now. thanks for the help – Akil S Feb 10 '23 at 09:02

0 Answers0