5 Aralık 2022 Pazartesi

HttpComponents HttpClientBuilder Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.http.impl.client.HttpClientBuilder;
setDefaultRequestConfig metodu
Tüm client için timeout ayarları yapılabilir.
Örnek
Şöyle yaparız
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

HttpGet request = new HttpGet("https://httpbin.org/get");

// 5 seconds timeout
RequestConfig requestConfig = RequestConfig.custom()
  .setConnectionRequestTimeout(5_000)
  .setConnectTimeout(5_000)
  .setSocketTimeout(5_000)
  .build();

try (CloseableHttpClient httpClient = HttpClientBuilder.create()
  .setDefaultRequestConfig(requestConfig)
  .build();
   CloseableHttpResponse response = httpClient.execute(request)) {
  ...
}
setUserAgent metodu
Şöyle yaparız.
CloseableHttpClient httpClient = HttpClients.custom()
  .setUserAgent(HTTP_USER_AGENT).
  .build();
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
setSSLSocketFactory metodu
Örnek
Şöyle yaparız
HttpClientBuilder builder = HttpClients.custom();
javax.net.ssl.SSLContext sslContext = SSLContext.getInstance("TLSv1.1");
javax.net.ssl.KeyManager[] clientKeyManagers = ...;
javax.net.ssl.TrustManager[] clientTrustManagers = ...;
sslContext.init(clientKeyManagers, clientTrustManagers, new SecureRandom());

builder.setSSLSocketFactory(
  new org.apache.http.conn.ssl.SSLConnectionSocketFactory(sslContext,
    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
);
CloseableHttpClient client = builder.build();

Hiç yorum yok:

Yorum Gönder