gpt4 book ai didi

java - Spring ClientHttpRequestInterceptor请求/响应为空

转载 作者:行者123 更新时间:2023-11-30 06:50:27 26 4
gpt4 key购买 nike

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

我目前有一个loggingRequestInterceptor类,它实现了ClientHttpRequestInterceptor,与sofiene here的答案非常相似。 .

然后,我将此拦截器添加为 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;
}
}

我的 RestTemplate 上的 Spring 属性:

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

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

最佳答案

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

关于java - Spring ClientHttpRequestInterceptor请求/响应为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42914176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com