Spring ClientHttpRequestInterceptor请求/响应为空

时间:2017-03-20 21:19:57

标签: java spring rest httprequest interceptor

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

我目前有一个实现ClientHttpRequestInterceptor的loggingRequestInterceptor类,非常类似于sofiene here的答案。

然后我在我的弹簧配置中将此拦截器添加为我的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>

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

1 个答案:

答案 0 :(得分:1)

解决方案:首先,请求正文是空白的,因为这是一个GET方法。其次,我还需要记录ResponseStatusCode,因为我收到204状态为No Content,因此导致响应空白。