Answer the question
In order to leave comments, you need to log in
How to write a filter to read body in response?
Hello. Help, please, to solve a problem.
I am writing a filter from which I could extract information from the outputStream
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();
}
}
HttpServletResponse httpResponse = (HttpServletResponse) response;
MyHttpServletResponseWrapper wrapper =
new MyHttpServletResponseWrapper(httpResponse);
chain.doFilter(request, wrapper);
String content = wrapper.toString();
Answer the question
In order to leave comments, you need to log in
The fact is that a stream can be read only once, that's why it's a stream. After reading the stream, you need to create a new stream from the same data, swap and feed it further down the chain.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question