春天的云端伪装拦截器

问题描述 投票:6回答:2

我创建了一个ClientHttpRequestInterceptor,用来拦截所有传出的RestTemplate请求和响应。我想把这个拦截器添加到所有传出的Feign请求和响应中。有什么方法可以做到这一点吗?

我知道有一个feign.RequestInterceptor,但我只能拦截请求而不能拦截响应。

我在Github上找到了一个FeignConfiguration类,它可以添加拦截器,但我不知道它是哪个maven依赖版本。

java maven spring-cloud netflix-feign
2个回答
0
投票

如果你想从spring cloud中使用feign,请使用以下方法 org.springframework.cloud:spring-cloud-starter-feign 作为你的依赖坐标。 目前修改响应的唯一方法是实现你自己的 feign.Client.


0
投票

在Spring Cloud OpenFeign中截取响应的实际例子。

  1. 创建一个自定义的 Client 延伸 Client.Default 如下图所示。
public class CustomFeignClient extends Client.Default {


    public CustomFeignClient(SSLSocketFactory sslContextFactory, HostnameVerifier hostnameVerifier) {
        super(sslContextFactory, hostnameVerifier);
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {

        Response response = super.execute(request, options);
        InputStream bodyStream = response.body().asInputStream();

        String responseBody = StreamUtils.copyToString(bodyStream, StandardCharsets.UTF_8);

        //TODO do whatever you want with the responseBody - parse and modify it

        return response.toBuilder().body(responseBody, StandardCharsets.UTF_8).build();
    }
}
  1. 然后使用自定义的 Client 的配置类中。
public class FeignClientConfig {


    public FeignClientConfig() { }

    @Bean
    public Client client() {
        return new CustomFeignClient(null, null);
    }

}
  1. 最后,在FeignClient中使用配置类。
@FeignClient(name = "api-client", url = "${api.base-url}", configuration = FeignClientConfig.class)
public interface ApiClient {

}

祝你好运

© www.soinside.com 2019 - 2024. All rights reserved.