Spring Cloud Feign Interceptor

Oreste picture Oreste · Jul 30, 2015 · Viewed 7.6k times · Source

I have created a ClientHttpRequestInterceptor that I use to intercept all outgoing RestTemplate requests and responses. I would like to add the interceptor to all outgoing Feign requests/responses. Is there a way to do this?

I know that there is a feign.RequestInterceptor but with this I can only intercept the request and not the response.

There is a class FeignConfiguration that I found in Github that has the ability to add interceptors but I don't know in which maven dependency version it is.

Answer

Seun Matt picture Seun Matt · Jun 11, 2020

A practical example of how to intercept the response in a Spring Cloud OpenFeign.

  1. Create a custom Client by extending Client.Default as shown below:
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. Then use the custom Client in a configuration class:
public class FeignClientConfig {


    public FeignClientConfig() { }

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

}
  1. Finally, use the configuration class in a FeignClient:
@FeignClient(name = "api-client", url = "${api.base-url}", configuration = FeignClientConfig.class)
public interface ApiClient {

}

Good luck