import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpRequest.Builder; import java.net.http.HttpResponse.BodyHandlers; import java.util.concurrent.CompletableFuture; public class ClientAsync { public static void get() { String url = "https://jsonplaceholder.typicode.com/users"; HttpClient client = HttpClient.newHttpClient(); Builder request = HttpRequest.newBuilder(); request.uri(URI.create(url)); request.GET(); CompletableFuture res = client.sendAsync(request.build(), BodyHandlers.ofString()) .thenApply(HttpResponse::body); System.out.println(res.join()); } public static void post() { String url = "https://jsonplaceholder.typicode.com/users"; HttpClient client = HttpClient.newHttpClient(); Builder request = HttpRequest.newBuilder(); request.uri(URI.create(url)); request.header("Content-Type", "application/json"); String body = "{ \"name\": \"John\", \"age\": 30 }"; request.POST(HttpRequest.BodyPublishers.ofString(body)); CompletableFuture res = client.sendAsync(request.build(), BodyHandlers.ofString()) .thenApply(HttpResponse::body); System.out.println(res.join()); } public static void put() { String url = "https://jsonplaceholder.typicode.com/users/1"; HttpClient client = HttpClient.newHttpClient(); Builder request = HttpRequest.newBuilder(); request.uri(URI.create(url)); request.header("Content-Type", "application/json"); String body = "{ \"name\": \"John\", \"age\": 30 }"; request.PUT(HttpRequest.BodyPublishers.ofString(body)); CompletableFuture res = client.sendAsync(request.build(), BodyHandlers.ofString()) .thenApply(HttpResponse::body); System.out.println(res.join()); } public static void delete() { String url = "https://jsonplaceholder.typicode.com/users/1"; HttpClient client = HttpClient.newHttpClient(); Builder request = HttpRequest.newBuilder(); request.uri(URI.create(url)); request.DELETE(); CompletableFuture res = client.sendAsync(request.build(), BodyHandlers.ofString()) .thenApply(HttpResponse::body); System.out.println(res.join()); } }