16 Ağustos 2023 Çarşamba

HttpClient.send metodu - HttpClient API

Giriş
GET veya POST için yaratılan HttpRequest nesnesini senkron olarak gönderir.

Cancel
Açıklaması şöyle. Java 20'den sonra Thread.interrupt ile yapılıyor
Since Java 16 it is possible to cancel a request by interrupting the thread that called HttpClient::send or by invoking cancel(true) on the CompletableFuture returned by HttpClient::sendAsync
Örnek
Şöyle yaparız. Burada Project Loom kullanılıyor. Aslında HttpClient  değil Virtual Thread iptal ediliyor.
import org.slf4j.LoggerFactory import java.net.URI import java.net.http.HttpResponse.BodyHandlers import java.net.http.{HttpClient, HttpRequest} import scala.sys.process._ object Run extends App { val log = LoggerFactory.getLogger(this.getClass) val client = HttpClient.newHttpClient() log.info("Starting virtual thread ...") val t = Thread.startVirtualThread(() => { log.info("Sending ...") val r = client.send( HttpRequest .newBuilder(new URI("http://localhost:8080/wait")) .GET().version(HttpClient.Version.HTTP_1_1) .build(), BodyHandlers.ofString() ) log.info(s"Received, body length: ${r.body().length}") }) Thread.sleep(1000) log.info("Interrupting ...") t.interrupt() log.info("Done.") }
send metodu
Örnek
Şöyle yaparız
HttpResponse<String> postData(String jsonStr, String endpoint, String accessToken) throws Exception { HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest httpRequest = HttpRequest.newBuilder() .header("Content-Type", "application/json") .header("Authorization", "Bearer " + accessToken) .uri(URI.create("https://...")) .POST(HttpRequest.BodyPublishers.ofString(jsonStr)) .build(); HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); return httpResponse; }

Hiç yorum yok:

Yorum Gönder