3
votes

I have to log response body and response headers. For that, I use Interceptor and the ContentCachingResponseWrapper class (I had also try with filter, but for the same result). When I combine both, I lose some headers informations but not if I use only Interceptor.

My dispatcherServlet :

@Component("dispatcherServlet")
public class MyDisPatcherServlet extends DispatcherServlet {
    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            super.doDispatch(request, new ContentCachingResponseWrapper(response));
        } catch (Exception e) {
            super.doDispatch(request,response);
        }
    }
}

When I use ContentCachingResponseWrapper in the postHandle of the Interceptor :

private Map<String, List<Object>> getHeaders(HttpServletResponse response){
    Map<String, List<Object>> headersList = new HashMap<>();
    Collection<String> headerNames = ((ContentCachingResponseWrapper)response).getHeaderNames();
    // Same if I use response.getHeaderNames()
    if (headerNames != null) {
        for(String headerName : headerNames){
            headersList.put(headerName, Arrays.asList(response.getHeaders(headerName))); 
        }
    }
    return headersList;
}

Headers result :

{Set-Cookie=[[JSESSIONID=109DE678B86611DE627B9B7B3B513DEF; Path=/service/services; HttpOnly]]}


If I unactivate the component MyDisPatcherServlet, and read directly header names from response :

private Map<String, List<Object>> getHeaders(HttpServletResponse response){
    Map<String, List<Object>> headersList = new HashMap<>();
    Collection<String> headerNames = response.getHeaderNames();
    if (headerNames != null) {
        for(String headerName : headerNames){
            headersList.put(headerName, Arrays.asList(response.getHeaders(headerName))); 
        }
    }
    return headersList;
}

Headers result :

{X-Frame-Options=[[DENY]], Transfer-Encoding=[[chunked]], Cache-Control=[[no-cache, no-store, max-age=0, must-revalidate]], X-Content-Type-Options=[[nosniff]], Connection=[[close]], Set-Cookie=[[JSESSIONID=9E2F642595202D87935F4CD5C089ADFE; Path=/service/services; HttpOnly]], Pragma=[[no-cache]], Expires=[[0]], X-XSS-Protection=[[1; mode=block]], Date=[[Mon, 23 Jul 2018 16:15:55 GMT]], Content-Type=[[application/json;charset=UTF-8]]}

Thanks in advance.

1
Were you able to retrieve the headers?jchips12

1 Answers

3
votes

You have to call copyBodyToResponse() before retrieving the headers.