Home Java javaTutorial Send HTTP requests and handle asynchronous responses using the new HttpClient in Java 13

Send HTTP requests and handle asynchronous responses using the new HttpClient in Java 13

Jul 31, 2023 pm 04:39 PM
java httpclient Asynchronous response handling

Send HTTP requests and handle asynchronous responses using the new HttpClient in Java 13

In Java 13, a new HttpClient API was introduced that provides a full-featured HTTP client that can send HTTP request and handle the returned asynchronous response. This new HttpClient API is very simple and flexible to use, more convenient than the previous HttpURLConnection.

First, we need to create a new HttpClient instance in the Java 13 environment. You can use the following code to create HttpClient:

HttpClient httpClient = HttpClient.newHttpClient();
Copy after login

Next, we can use the created HttpClient object to send HTTP requests. We can send GET requests, POST requests, etc. Taking sending a GET request as an example, we can use the following code snippet:

URI uri = URI.create("http://www.example.com");
HttpRequest request = HttpRequest.newBuilder()
                .uri(uri)
                .build();
Copy after login

In the above code, we create a URI object to represent the requested URL, and use the HttpRequest.newBuilder() method to create an HttpRequest object. Then, we can use the sendAsync() method of the HttpClient object to send an asynchronous request and get a CompletableFuture object through which the asynchronous response can be processed.

CompletableFuture<HttpResponse<String>> future = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString());
Copy after login

In the above code, we use the sendAsync() method of the HttpClient object to send the request, and pass an HttpResponse.BodyHandlers.ofString() object to specify how the response is processed (a string is used here form). The sendAsync() method immediately returns a CompletableFuture object representing the result of the asynchronous operation. We can use this CompletableFuture object to handle asynchronous responses.

We can block waiting for the asynchronous response to complete and obtain the response object by calling the get() method of the CompletableFuture object. The following is a sample code:

try {
    HttpResponse<String> response = future.get();
    System.out.println("Response Code: " + response.statusCode());
    System.out.println("Response Body: " + response.body());
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}
Copy after login

In the above code, we call the future.get() method to obtain the asynchronous response object. If the asynchronous operation has not yet completed, the get() method will block waiting until the operation is completed. Once the asynchronous operation is completed, we can use the HttpResponse object to obtain the response status code and response body.

In addition to using CompletableFuture objects, we can also use callback functions to handle asynchronous responses. Java 13's HttpClient API provides two ways to register callback functions, namely thenApply() and thenAccept(). The following is a sample code using thenApply():

CompletableFuture<HttpResponse<String>> future = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString());
future.thenApply(response -> {
    System.out.println("Response Code: " + response.statusCode());
    System.out.println("Response Body: " + response.body());
    return response;
});
Copy after login

By using the thenApply() method, we can define a callback function to handle asynchronous responses. When the asynchronous response is completed, the callback function will be called, and we can process the response in the callback function.

To summarize, it is very simple to use the new HttpClient in Java 13 to send HTTP requests and handle asynchronous responses. We just create an HttpClient object, use it to send the request, and then handle the asynchronous response through the CompletableFuture object or callback function. This new HttpClient API provides very flexible and powerful features that make it easier to interact with web services. At the same time, it also provides better performance and resource management.

I hope the sample code in this article can help you get started with the new HttpClient API in Java 13 and play a role in actual projects.

The above is the detailed content of Send HTTP requests and handle asynchronous responses using the new HttpClient in Java 13. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Square Root in Java

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Perfect Number in Java

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Random Number Generator in Java

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Armstrong Number in Java

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Weka in Java

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Smith Number in Java

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

Java Spring Interview Questions

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Break or return from Java 8 stream forEach?

See all articles