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

王林
Release: 2023-07-31 16:39:21
Original
894 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template