clienthttpprequestinterceptor不拦截

zed5wv10  于 2021-07-11  发布在  Java
关注(0)|答案(0)|浏览(233)

我试图截获http请求以便记录响应信息。我按照这个教程做了所有的事情(https://www.briansdevblog.com/2019/12/spring-resttemplate-request-response-logging/)拦截器不拦截。这是我的密码:

@Component()

公共类logginginterceptor实现clienthttprequestinterceptor{

protected final Logger LOG = LoggerFactory.getLogger(this.getClass());

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    logRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    logResponse(response);

      return response;
}

private void logRequest(HttpRequest request, byte[] body) throws IOException {
    LOG.debug("===========================request begin================================================");
    LOG.debug("URI         : {}", request.getURI());
    LOG.debug("Method      : {}", request.getMethod());
    LOG.debug("Headers     : {}", request.getHeaders());
    LOG.debug("Request body: {}", new String(body, "UTF-8"));
    LOG.debug("==========================request end================================================");

  }

private void logResponse(ClientHttpResponse response) throws IOException {
    LOG.info("============================response begin==========================================");
    LOG.info("Status code  : {}", response.getStatusCode());
    LOG.info("Status text  : {}", response.getStatusText());
    LOG.info("Headers      : {}", response.getHeaders());
    LOG.info("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
    LOG.info("=======================response end=================================================");

}

}

@Configuration

公共类restclientconfig{

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();

    List<ClientHttpRequestInterceptor> interceptors
      = restTemplate.getInterceptors();

    if (CollectionUtils.isEmpty(interceptors)) {
        interceptors = new ArrayList<>();
    }
    interceptors.add(new LoggingInterceptor());
    restTemplate.setInterceptors(interceptors);

    restTemplate.getInterceptors().forEach(e -> System.out.println(e.getClass()));

    return restTemplate;
}

}
有人知道为什么不起作用吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题