Spring-无法在自定义ClientHttpRequestInterceptor实现类中记录请求正文

时间:2019-03-20 11:55:48

标签: java spring spring-mvc logging interceptor

我创建了一个名为HttpInterceptor的类名,它实现了ClientHttpRequestInterceptor。此类的目的是拦截resttemplate调用,然后重写Intercept方法。在执行期间,我无法登录请求正文。但是,有一个从前端发送的请求正文。

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

    String requestBody = "";
    String url = request.getURI().toString();

    ClientHttpResponse response = null;
    Date timeIn = new Date();
    String responseBody = "";

    // I have also try new String(body, "UTF-8") and many others.
    requestBody = new String(body, Charset.forName("UTF-8"));

    logger.info("=============================REQUEST BEGIN==============================================");
    logger.info("URI         :" + url);
    logger.info("Method      :" + request.getMethod());
    logger.info("Headers     :" + request.getHeaders());
    logger.info("Request body:" + requestBody);
    logger.info("=============================REQUEST END================================================");

    response = execution.execute(request, body);

    responseBody = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
        //new String(ByteStreams.toByteArray(response.getBody()), Charset.forName("UTF-8"))

    logger.info("=============================RESPONSE BEGIN=============================================");
    logger.info("Status code  : " + response.getStatusCode());
    logger.info("Status text  : " + response.getStatusText());
    logger.info("Headers      : " + response.getHeaders());
    logger.info("Response body: " + responseBody);
    logger.info("=============================RESPONSE END===============================================");

    return response;
}

其余模板的初始化如下:

RestTemplate restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));

restTemplate.setInterceptors(Collections
            .singletonList(new HttpInterceptor()));

我在StackOverflow Why my custom ClientHttpRequestInterceptor with an empty response 上也发现了类似的问题,但这与我想要的完全不同。

1 个答案:

答案 0 :(得分:0)

这似乎是一个非常有趣的解决方案,但没有得到它的可能性。我在登录请求正文时遇到困难,但是找到了一个解决方案,我必须在RestTemplate初始化中进行一次更改来构建完整的解决方案,然后还原并再次构建该解决方案,从而解决了我的问题。以下是更改:

构建没有此行new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())

的完整解决方案
RestTemplate restTemplate = new RestTemplate();

restTemplate.setInterceptors(Collections
            .singletonList(new HttpInterceptor()));

然后像这样恢复到最初的状态,然后构建解决我的问题的解决方案:

RestTemplate restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));

restTemplate.setInterceptors(Collections
            .singletonList(new HttpInterceptor()));

注意:我已经使用不同的输入(即请求)测试了该解决方案,并且该解决方案可以正常运行。