0

I'm trying got response data in Spring HandlerInterceptor's afterCompletion() but got the data is empty;

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    try {
         ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
         byte[] contentAsByteArray = responseWrapper.getContentAsByteArray();
    } finally {
        SessionManagerThreadLocal.remove();
    }
}

contentAsByteArray byte[] is empty

What should I do ? Thanks

Mr.zhu
  • 1
  • Use a filter and wrap before the chain continues. You can only read the response once. Wrapping in the interceptor won't help. – M. Deinum Aug 12 '21 at 09:17

1 Answers1

0

In your description you said you are trying to get response but in code you are using request and request mapper. If you want to use request you need to add filter which will store request in wrapper

@Component
public class CachingRequestBodyFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper((HttpServletRequest) servletRequest);

        //this line is necessary to cache InputStream
        wrappedRequest.getInputStream();

        chain.doFilter(wrappedRequest, servletResponse);
    }
}
Krzysztof K
  • 736
  • 4
  • 19