Spring Cloud Feign Interceptor

10,567

Solution 1

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

Solution 2

If you want to use feign from spring cloud, use org.springframework.cloud:spring-cloud-starter-feign as your dependency coordinates. Currently the only way to modify the response is to implement your own feign.Client.

Share:
10,567
Oreste
Author by

Oreste

Updated on June 09, 2022

Comments

  • Oreste
    Oreste almost 2 years

    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.

  • Oreste
    Oreste almost 9 years
    Thanks @spencergibb. I'm currently using Feign with org.springframework.cloud:spring-cloud-starter-feign.