Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Cloud Feign Interceptor

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.

like image 678
Oreste Avatar asked Jul 30 '15 11:07

Oreste


1 Answers

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

like image 190
Seun Matt Avatar answered Sep 28 '22 19:09

Seun Matt