How can I read an HttpServletReponses output stream?

Add this to the filter java file.

static class MyHttpServletResponseWrapper 
  extends HttpServletResponseWrapper {

  private StringWriter sw = new StringWriter(BUFFER_SIZE);

  public MyHttpServletResponseWrapper(HttpServletResponse response) {
    super(response);
  }

  public PrintWriter getWriter() throws IOException {
    return new PrintWriter(sw);
  }

  public ServletOutputStream getOutputStream() throws IOException {
    throw new UnsupportedOperationException();
  }

  public String toString() {
    return sw.toString();
  }
}

Use the follow code:

HttpServletResponse httpResponse = (HttpServletResponse) response;
MyHttpServletResponseWrapper wrapper = 
  new MyHttpServletResponseWrapper(httpResponse);

chain.doFilter(request, wrapper);

String content = wrapper.toString();

The content variable now has the output stream. You can also do it for binary content.


Spring now has feature for it . All you need to do is use [ContentCachingResponseWrapper], which has method public byte[] getContentAsByteArray() .

I Suggest to make WrapperFactory which will allow to make it configurable, whether to use default ResponseWrapper or ContentCachingResponseWrapper.


I don't much know that you can get data out of an HttpServletResponse object as such. It may make more sense to structure your application such that requests are proxied to the appropriate handlers and passed about with data transfer objects, from which you can build the appropriate final response. In this manner, you never modifiy more than one response object or need to read from such.

Not a direct answer, I know, but that's how I'd do it give the question.