我创建了一个ClientHttpRequestInterceptor,用来拦截所有传出的RestTemplate请求和响应。我想把这个拦截器添加到所有传出的Feign请求和响应中。有什么方法可以做到这一点吗?
我知道有一个feign.RequestInterceptor,但我只能拦截请求而不能拦截响应。
我在Github上找到了一个FeignConfiguration类,它可以添加拦截器,但我不知道它是哪个maven依赖版本。
如果你想从spring cloud中使用feign,请使用以下方法 org.springframework.cloud:spring-cloud-starter-feign
作为你的依赖坐标。 目前修改响应的唯一方法是实现你自己的 feign.Client
.
在Spring Cloud OpenFeign中截取响应的实际例子。
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();
}
}
Client
的配置类中。public class FeignClientConfig {
public FeignClientConfig() { }
@Bean
public Client client() {
return new CustomFeignClient(null, null);
}
}
@FeignClient(name = "api-client", url = "${api.base-url}", configuration = FeignClientConfig.class)
public interface ApiClient {
}
祝你好运