Spring ClientHttpRequestInterceptor request/response empty



我想在我的应用程序中获取 REST 请求和响应正文以进行日志记录。

我目前有一个实现ClientHttpRequestInterceptor的loggingRequestInterceptor类,与sofiene在这里的答案非常相似。

然后,我将这个拦截器作为属性添加到我的 Spring 配置中的 Rest 模板中。

我的代码如下所示:

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoggingRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
response = log(request, body, response);
return response;
}
private ClientHttpResponse log(final HttpRequest request, final byte[] body, final ClientHttpResponse response) throws IOException {
final ClientHttpResponse responseCopy = new BufferingClientHttpResponseWrapper(response);
StringBuilder builder = new StringBuilder();
builder.append("Method: ").append(request.getMethod().toString());
builder.append("URI: ").append(request.getURI().toString());
builder.append("Request Body: ").append(new String(body,"UTF-8"));
builder.append("Response body: ").append(convertStreamToString(responseCopy.getBody()));
logger.info(builder.toString());
return responseCopy;
}
}

我的休息模板上的弹簧属性:

<property name="interceptors">
<list>
<bean class="com.company.projectName.service.api.rest.io.impl.LoggingRequestInterceptor" />                       
</list>
</property>

但是,在我的所有休息调用中,我记录了方法和 URI,但正文和响应正文为空。从请求和响应中获取正文的正确方法是什么,以便允许我的应用程序记录此信息。

解决方案:首先,请求正文为空,因为这是一个 GET 方法。其次,我还需要记录响应状态代码,因为我收到的状态为 204,即无内容,从而导致响应正文为空。

最新更新