How to use custom ApacheHttpClient with Feign?

4.6k Views Asked by At

I've tried to add a custom HttpClient via configuration:

 @Bean
 public CloseableHttpClient httpClient() {
    RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000)
                .setConnectionRequestTimeout(15000)
                .build();

    Header header = new BasicHeader("Test", "Test");
    Collection<Header> headers =Arrays.asList(header);        
    return HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setDefaultHeaders(headers)
                .build();
 }

but still, my custom added default header doesn't appear in the request.

My Feign client interface looks like below:

@FeignClient(name = "example", 
             url = "${client.example.api}", 
             decode404 = false, 
             configuration = FeignClientConfiguration.class)
public interface ExampleFeignProxy{

    @PostMapping(path = "/create")
    @Headers("Content-Type: application/json")
    String Create(
            @RequestBody ExampleDTO exampleDto,
            @RequestHeader("access-token") String token);
}

but when I make request to the Create method, request fails, when I inspect inside configuration.errordecoder, it shows feign is adding an extra header Content-Length also to the request. How can I remove default headers from all methods inside my feign client?

To make it clear - as shown above, only two headers should have been present on the request object

  • Content-Type

  • Access-Token

but Feign somehow adds Content-Length as well.

Is there a configuration somewhere I need to set?

2

There are 2 best solutions below

0
Manish Mishra On BEST ANSWER

Actually, it was a misunderstanding, above configuration was always working, I was not parsing the error properly. The error returned was actually from the api.

All I had to do was to properly specify the errordecoder.

0
Maqsudjon Mamarasulov On

Try this:

Maven dependency:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-hc5</artifactId>
        </dependency>

Code:

public class FeignConfig {
    @Bean
    public Client client () {
        return new ApacheHttp5Client(httpClient());
    }

    public CloseableHttpClient httpClient() {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000)
                .setConnectionRequestTimeout(15000)
                .build();

        Header header = new BasicHeader("Test", "Test");
        Collection<Header> headers =Arrays.asList(header);        
        return HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setDefaultHeaders(headers)
                .build();
    }
}