【问题标题】:How to get ClientHttpRequestInterceptor working?如何让 ClientHttpRequestInterceptor 工作?
【发布时间】:2020-10-24 08:13:22
【问题描述】:

我正在尝试让 ClientHttpRequestInterceptor 跟随 Baeldung's Spring RestTemplate Request/Response Logging 工作。问题是 ClientHttpRequestInterceptor 永远不会被调用。

我对 HandlerInterceptor 和 HandlerInterceptorAdapter 拦截器也有类似的问题。问题是我需要添加一个监听器,我发现的 99% 的文章都没有提到。

@Configuration
public class ListenerConfig implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext sc) throws ServletException {
        sc.addListener(new RequestContextListener());
    }
}

我猜想 Spring 发生了一些变化,默认情况下监听器不在那里。

有人知道 ClientHttpRequestInterceptor 的监听器吗?

拦截器:

public class LoggingInterceptor implements ClientHttpRequestInterceptor {

    static Logger LOGGER = LoggerFactory.getLogger(LoggingInterceptor.class);

    @Override
    public ClientHttpResponse intercept(
            HttpRequest req, byte[] reqBody, ClientHttpRequestExecution ex) throws IOException {
        LOGGER.debug("Request body: {}", new String(reqBody, StandardCharsets.UTF_8));
        ClientHttpResponse response = ex.execute(req, reqBody);
        InputStreamReader isr = new InputStreamReader(
          response.getBody(), StandardCharsets.UTF_8);
        String body = new BufferedReader(isr).lines()
            .collect(Collectors.joining("\n"));
        LOGGER.debug("Response body: {}", body);
        return response;
    }
}

RestClientConfig:

@Configuration
public class 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);
        return restTemplate;
    }
}

这可能与ClientHttpRequestInterceptor not called in springboot有关。

【问题讨论】:

  • 如果您的RestTemplate 工作正常但没有添加拦截器,请将您使用RestTemplate 的代码部分放入其中。
  • 这是一个简单的 REST 服务。没有RestTemplate 代码,只有一个带有@RestController 注释的控制器。在映射方法中带有@RequestBody,应该调用RestTemplate。控制器工作正常。
  • 你的控制器中有@Autowired它吗?
  • 是的 @Autowired 用于服务,控制器调用。该服务构建一个自定义响应模型,控制器返回该模型,Spring 将其转换为响应的 JSON 正文。

标签: java spring spring-boot resttemplate


【解决方案1】:

Spring RestTemplate 拦截器仅在客户端(消费者)端或在测试充当您拥有RestTemplate 的客户端的测试中工作。我正在尝试登录服务器(生产者)端。因此,不需要RestTemplate

Bealdung.com 的 Loredana 很高兴给我发电子邮件并指出,我有一个误解。

我在某处捡到Spring 使用RestTemplate 对 Rest 控制器中的 POJO 进行自动解码和编码。这是不正确的。

@Tashkhisi 还指出评论中缺少RestTempale

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-04
    • 2011-04-07
    • 2011-07-27
    • 2011-03-08
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多