Spring Boot 响应主体写入方法ServerHttpResponse之前的响应主体建议具有空状态和标头值

zi8p0yeb  于 2023-03-02  发布在  Spring
关注(0)|答案(1)|浏览(269)
    • bounty将在6天后过期**。回答此问题可获得+50声望奖励。Albin希望引起更多人关注此问题。

我正在为我的Spring引导REST API编写一个类,通过扩展ResponseBodyAdvice来记录响应。因为我能够通过重写beforeBodyWrite方法来记录响应主体。但是在同一方法中,ServerHttpResponse参数没有给出HTTP响应状态。以下是我的代码片段

@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;
}

正如你所看到的,我正在尝试记录响应代码和响应头,但是这些日志都是空值。

4c8rllxm

4c8rllxm1#

我尝试复制您的问题,状态代码记录良好,标题返回为空。
使用response.getHeaders()而不是((ServletServerHttpResponse) response).getServletResponse().getHeaderNames()将记录响应标头及其值:

@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;
}

示例日志:

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"]

希望能有所帮助,或者你能提供更多的信息,以便进一步探讨这个问题。

相关问题