1

I want to read the response body in my interceptor for logging.After I searched some answers, I tend to use ContentCachingResponseWrapper.here is my code:

public class CustomerInterceptor extends HandlerInterceptorAdapter{
    public void poseHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        byte[] contentAsByteArray = responseWrapper.getContentAsByteArray();
        ...
    }

But when I debug it .I got responseWrapper with content "".But In the postman I get the response body. Then I go to the source code.

private final FastByteArrayOutputStream content = new FastByteArrayOutputStream(1024);

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

It seems that I didn't init the content.I know something is wrong in my code.My question is how to use ContentCachingResponseWrapper correctly?

linghu
  • 133
  • 3
  • 16
  • Thank for your reply. I had read that answer. My question is in the interceptor , the `contentAsByteArray` is an empty String. – linghu Aug 23 '17 at 03:24
  • 1
    You need to wrap response with this wrapper using a filter, interceptor wont do. This is displayed in the question I linked. You can use interceptor to log result, but this seems unnecessary since you still need a filter for wrapping.. – chimmi Aug 23 '17 at 06:25
  • It seems that you are right. But why in interceptor it doesn't works,I'm confuse about that. – linghu Aug 24 '17 at 03:47
  • 1
    Because with filter you can pass your wrapper further using 'filterChain.doFilter', but with interceptor you cannot. – chimmi Aug 24 '17 at 04:14
  • In that case , can I replace the `HttpServletRequest` and `HttpServletResponse` in a customer `DispatcherServlet`? – linghu Aug 24 '17 at 06:49
  • No, filter is the only option. – chimmi Aug 24 '17 at 06:57

0 Answers0