8 Eylül 2023 Cuma

HttpClient.Builder Sınıfı - HttpClient API

connectTimeout metodu
 Açıklaması şöyle
The Java 11 HTTP Client API allows developers to configure timeouts for their HTTP requests. This is particularly useful when dealing with scenarios where a response is expected within a certain time frame. By setting appropriate timeout values, applications can avoid waiting indefinitely for a response and gracefully handle timeout scenarios.
Örnek
Şöyle yaparız
HttpClient client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(10))
    .build();
Örnek
Şöyle yaparız
HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(20)) .build(); HttpRequest httpRequest = HttpRequest.newBuilder() .GET() .uri(URI.create("https://...")) .build(); HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); System.out.println(httpResponse.body());
followRedirects metodu
Açıklaması şöyle
The Java 11 HTTP Client API simplifies the handling of redirects in HTTP requests. By default, the API automatically follows redirects, allowing developers to easily handle scenarios where the requested resource has been moved or requires authentication. The API also provides options to control the behavior of redirects, such as maximum follow limit and redirect policy customization.
Örnek
Redirect.NORMAL şu anlama gelir
Always redirect, except from HTTPS URLs to HTTP URLs.
Şöyle yaparız
HttpClient client = HttpClient.newBuilder()
    .followRedirects(Redirect.NORMAL)
    .build();
proxy metodu
Açıklaması şöyle
The Java 11 HTTP Client API supports working with proxies, enabling applications to route their HTTP requests through a proxy server. Developers can configure the API to use a specific proxy server, provide authentication credentials if required, and handle scenarios where multiple proxy servers are available.
Örnek
Şöyle yaparız
import java.net.ProxySelector;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
 
HttpClient HTTP_CLIENT = HttpClient.newBuilder()
   // default
  .version(HttpClient.Version.HTTP_2)
  // Always redirect, except from HTTPS URLs to HTTP URLs.
  .followRedirects(HttpClient.Redirect.NORMAL) 
  .proxy(ProxySelector.getDefault())
  .build();

Örnek
Şöyle yaparız
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));

HttpClient client = HttpClient.newBuilder()
    .proxy(proxy)
    .build();
sslContext metodu
HttpClient.Builder Sınıfı SSL yazısına taşıdım

Hiç yorum yok:

Yorum Gönder