0

I am using for my project the version 2.0.2 release of springboot. I need to use HttpClient class for my project. could you help me please how to enable httpClient for this release?

Thanks in advance,

BackToReal
  • 143
  • 1
  • 5
  • 15

1 Answers1

1

A hint that could help you.

Start by registering an HttpClient bean in a Spring Config class like this:

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;


@Configuration
public class SpringConfiguration {

  @Bean
  public HttpClient httpClient() {
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30 * 1000).build();
    return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
  }

}

Then you can access by two ways:

"Autowirering" the field in the component

@Autowired
private HttpClient httpClient;

Or injecting it in the component's constructor like this:

@Service
public class MyClass{
  private final HttpClient httpClient;

  @Autowired
  public MyClass(HttpClient httpClient){
    this.httpClient = httpClient;
  }
}

I personally prefer the second approach which makes it more understandable and easier at the moment of testing, you just provide a mock to the instance of the class you want to test.

Théo camb.
  • 198
  • 1
  • 5