16 Ağustos 2023 Çarşamba

HttpClient.sendAsync metodu - HttpClient API

Giriş
GET veya POST için yaratılan HttpRequest nesnesini asenkron olarak gönderir. Metodun imzası şöyle
public abstract <T> CompletableFuture<HttpResponse<T>> sendAsync​( HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)
Cancel
Açıklaması şöyle. Java 16'dan sonra CompletableFuture.cancel() ile iptal ediliyor.
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
val client = HttpClient.newHttpClient() log.info("Sending ...") val f = client.sendAsync( HttpRequest .newBuilder(new URI("http://localhost:8080/stream")) .GET() .version(HttpClient.Version.HTTP_1_1) .build(), BodyHandlers.ofString() ) log.info("Sent ...") Thread.sleep(1000) f.cancel(true) // java 11: no effect; java 20: works
sendAsync metodu
Örnek
Şöyle yaparız
HttpRequest request = ...; client.sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println) .join();
Örnek
Şöyle yaparız
static <T> CompletableFuture<List<T>> fetchAsync(String url) { // create a client var client = HttpClient.newHttpClient(); // create a request var request = HttpRequest .newBuilder(URI.create(url)) .header("accept", "application/json") .build(); // use the client to send the request final var response = client .sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenApply(App::<T>parseJSON); // the response: return response; }
parseJSON şöyledir
private static <T> List<T> parseJSON(String textResponse) { final ObjectMapper objectMapper = new ObjectMapper(); List<T> objects = new ArrayList<>(); try { objects = objectMapper.readValue(textResponse, new TypeReference<List<T>>() {}); } catch (JsonMappingException | JsonProcessingException e) { ... } return objects; }
İki tane isteği paralel çalıştırmak için şöyle yaparız
CompletableFuture<List<Book>> booksFuture = fetchAsync( "https://[your-api-here]/api/books" ); CompletableFuture<List<Author>> authorsFuture = fetchAsync( "https://[your-api-here]/api/authors" ); booksFuture.get(); authorsFuture.get();




Hiç yorum yok:

Yorum Gönder