10 Ocak 2022 Pazartesi

HttpClient Sınıfı - Java 11 İle Geliyor - HttpClient API

Giriş
Şu satırı dahil ederiz.
import java.net.http.HttpClient;
1. HttpRequest nesnesi yaratılır. Bu nesne GET, POST gibi bir isteği temsil ederi
2. HttpClient nesnesi yaratılır. Bu nesnenin send() veya sendAsync() metodu çağrılır. 
3. Çağrı sonucunda HttpResponse nesnesi elde edilir. 
4. HttpResponse sınıfı şöyle kullanılır

Örnek - String HttpResponse
Şöyle yaparız
HttpClient client = HttpClient.newHttpClient();

HttpRequest request = ...;

HttpResponse<String> responseOfString = client.send(request,
  HttpResponse.BodyHandlers.ofString());


System.out.println("Status code: " + responseOfString.statusCode());
System.out.println("Body: " + responseOfString.body());
Örnek - Stream HttpResponse
Şöyle yaparız
HttpResponse<InputStream> getResponse(HttpRequest request) 
  throws IOException, InterruptedException {
  return HttpClient
    .newHttpClient()
    .send(request, HttpResponse.BodyHandlers.ofInputStream());
}

HttpResponse<InputStream> response = getResponse(request);

System.out.println("status code: " + response.statusCode());
InputStream body = response.body();

newBuilder metodu
HttpClient.Builder Sınıfı yazısına taşıdım


newHttpClient metodu
Şöyle yaparız
HttpClient client = HttpClient.newHttpClient();
send metodu
send metodu yazısına taşıdım

sendAsync metodu
sendAsync metodu yazısına taşıdım

Java 21
Açıklaması şöyle
The java.net.http.HttpClient now implements AutoClosable, making it usable in a try-with-resources block.

There are also 5 new related methods:
İmzası şöyle
// Initiates an orderly shutdown by completing previously submitted
// request but not accepting new ones.
void close()

// Initiates a graceful shutdown and returns immediately
void shutdown()

// Initiates an immediate shutdown and tries to interrupt any active
// operation. Returns immediately, too.
void shutdownNow()

// Waits for the client to terminate for the given duration.
// Returns true if the client was terminated in time.
boolean awaitTermination(Duration duration)

// Checks if a client is terminated.
boolean isTerminated()
Açıklaması şöyle
Instances obtained via HttpClient.newHttpClient() or HttpClient.newBuilder() provide best-effort implementations of these methods.






Hiç yorum yok:

Yorum Gönder