0
@Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        StringWriter writer = new StringWriter();
        IOUtils.copy(request.getInputStream(), writer, "UTF-8");
        rawRequest = writer.toString();

        System.out.println("raw Request   :" + rawRequest);

        chain.doFilter(req, res);

    }

When I run this, I get the raw Request string in proper format, but when I try to get this raw Request anywhere outside the doFilter method, it returns null.

Is there a way I can get this String outside the doFilter method as well. I tried passing this String to a new method but nothing works.

sheldonzy
  • 5,505
  • 9
  • 48
  • 86
  • 1
    Possible duplicate of [How to read request.getInputStream() multiple times](https://stackoverflow.com/questions/4449096/how-to-read-request-getinputstream-multiple-times) – alfcope Oct 06 '17 at 10:44
  • 1
    what do you mean passing it to a new method? show more code.. – Jonathan Laliberte Oct 06 '17 at 18:36

1 Answers1

1

One simple solution would be to just add the raw request string that you just read into a ServletRequest attribute:

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    StringWriter writer = new StringWriter();
    IOUtils.copy(request.getInputStream(), writer, "UTF-8");
    rawRequest = writer.toString();

    System.out.println("raw Request   :" + rawRequest);

    req.setAttribute("rawRequest", rawRequest);

    chain.doFilter(req, res);
}

You can then recover it anywhere that you have access to the request object:

String rawRequest = (String)req.getAttribute("rawRequest");
Steve C
  • 18,876
  • 5
  • 34
  • 37