How can I read an HttpServletReponses output stream?

后端 未结 4 812
傲寒
傲寒 2020-11-27 19:43

I want to make a Servlet filter that will read the contents of the Response after it\'s been processed and completed and return that information in XML or PDF or whatever.

4条回答
  •  孤城傲影
    2020-11-27 20:02

    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.

提交回复
热议问题