Search code examples
spring-bootspring-mvcspring-rest

ResponseBodyAdvice beforeBodyWrite method ServerHttpResponse has null status and header values


I am writing a class for my Spring boot REST API to log the response by extending the ResponseBodyAdvice. In that I am able to log the response body by overriding the beforeBodyWrite method. But in that same method the ServerHttpResponse parameter is not giving the HTTP response status. Following is my code snippet

@ControllerAdvice
@Slf4j
public class ResponseBodyInterceptor implements ResponseBodyAdvice<Object> {

@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
}

@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
                              MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
                              ServerHttpRequest request, ServerHttpResponse response) {
    log.info("response code is {}", ((ServletServerHttpResponse) response).getServletResponse().getStatus());
    log.info("response headers are {}", ((ServletServerHttpResponse) response).getServletResponse().getHeaderNames());
    return body;
}

As you can see I am trying to log the response code and response headers, but those logs are coming with empty value. Could please help me in this


Solution

  • I tried to replicate your issue, the status code logged fine, the headers returned empty.

    Using response.getHeaders() instead of ((ServletServerHttpResponse) response).getServletResponse().getHeaderNames() would log the response headers with their values:

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter arg1, MediaType arg2,
      Class<? extends HttpMessageConverter<?>> arg3, ServerHttpRequest arg4, ServerHttpResponse response) {
        log.info("response code is {}", ((ServletServerHttpResponse) response).getServletResponse().getStatus());
        log.info("response headers are {}", response.getHeaders());
        return body;
    }
    

    sample logs:

    2023-03-01 11:29:44.527 INFO 48464 --- c.e.demo.config.ResponseBodyInterceptor  : response code is 400
    2023-03-01 11:29:44.527 INFO 48464 --- c.e.demo.config.ResponseBodyInterceptor  : response headers are [HEADER:"TEST"]
    

    Hope it would be of some help, or if you can provide more information for further explorations on the issue.