java native httpclient utils

Java Native HttpClient is a library introduced in Java 11 to provide a modern, efficient, and easy-to-use API for making HTTP requests. Here are some utility methods you can use with Java Native HttpClient:

  • Creating an HttpClient:

HttpClient client = HttpClient.newHttpClient();

  • Creating an HttpRequest:

HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://example.com")) .header("Content-Type", "application/json") .GET() .build();

  • Sending a GET request and receiving a response:

HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); int statusCode = response.statusCode(); String responseBody = response.body();

  • Sending a POST request with JSON payload:

String jsonPayload = "{\"name\": \"John\", \"age\": 30}"; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://example.com/api")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonPayload)) .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());

  • Handling response headers:

HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); Map> headers = response.headers().map(); List contentType = headers.get("Content-Type");

  • Handling timeouts:

HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .build();

  • Asynchronous requests:

CompletableFuture> future = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); future.thenAccept(response -> { int statusCode = response.statusCode(); String responseBody = response.body(); });

These are some of the commonly used utility methods in Java Native HttpClient. However, there are many more options and configurations available depending on your specific requirements. You can refer to the official Java documentation for more details on Java Native HttpClient: java.net.http (Java SE 11 & JDK 11 )

你可能感兴趣的:(java,servlet,开发语言)