0

I have a filter with method

public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain)

My goal is to print to the console the content of rep. I've tried to do that via

((HttpServletResponse) rep).getWriter()

But getWriter method do something different.

I also wrote a wrapper:

class HtmlResponseWrapper extends HttpServletResponseWrapper {
    private final ByteArrayOutputStream capture;
    private ServletOutputStream output;
    private PrintWriter writer;

    public HtmlResponseWrapper(HttpServletResponse response) {
        super(response);
        capture = new ByteArrayOutputStream(response.getBufferSize());
    }

    @Override
    public ServletOutputStream getOutputStream() {
        if (writer != null) {
            throw new IllegalStateException("getWriter() has already been called on this response.");
        }
        if (output == null) {
            output = new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    capture.write(b);
                }
            };
        }
        return output;
    }
    ...
}

But invocation os new HtmlResponseWrapper(rep).getOutputStream() gains not exactly what do I want.

So my question is: how can I print the real body of response?

Finkelson
  • 2,921
  • 4
  • 31
  • 49
  • Possible duplicate of [How can I read an HttpServletReponses output stream?](http://stackoverflow.com/questions/701681/how-can-i-read-an-httpservletreponses-output-stream) – Andres Oct 21 '15 at 13:24
  • The Solution from the answer does not fit me. I've already tried it. – Finkelson Oct 21 '15 at 13:33

1 Answers1

0

Most probably you won't be able to do it. The container can even decide to start flushing the output and removing (a part of) it from the memory (depending on buffer sizes) at the time when your filter is executed.

erosb
  • 2,943
  • 15
  • 22