Java Asynchronous HttpClient Overview and Tutorial - sendAsync()

Java is very powerful. Every release brings so many new APIs and functionalities to core Java SDK. In this tutorial we will go over Java Asynchronous HttpClient Example and details.

Here is a tutorial on Java Synchronous HttpClient example.

sendAsync() sends the given request asynchronously using this client with the given response body handler.
Equivalent to: sendAsync(request, responseBodyHandler, null).

Let’s get started:

  • Create file CrunchifyJavaAsynchronousHTTPClient.java
package crunchify.com.tutorial;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author Crunchify.com
 * Overview and Simple Java Asynchronous HttpClient Client Tutorial
 */

public class CrunchifyJavaAsynchronousHTTPClient {

    private static final HttpClient crunchifyHttpClient = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .connectTimeout(Duration.ofSeconds(5))
            .build();

    // HttpClient: An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder.

    // Duration: A time-based amount of time, such as '5 seconds'.
    public static void main(String[] args) {

        // Async HTTPClient Example
        crunchifyAsyncHTTPClient();
    }

    private static void crunchifyAsyncHTTPClient() {

        HttpRequest crunchifyRequest = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("https://crunchify.com/wp-content/java/crunchify-java-httpclient-tutorial.html"))
                .setHeader("User-Agent", "Crunchify Java Aysnc HTTPClient Example...")
                .build();

        CompletableFuture<HttpResponse<String>> crunchifyAsyncResponse = null;

        // sendAsync(): Sends the given request asynchronously using this client with the given response body handler.
        //Equivalent to: sendAsync(request, responseBodyHandler, null).
        crunchifyAsyncResponse = crunchifyHttpClient.sendAsync(crunchifyRequest, HttpResponse.BodyHandlers.ofString());

        String crunchifyAsyncResultBody = null;
        int crunchifyAsyncResultStatusCode = 0;

        try {
            crunchifyAsyncResultBody = crunchifyAsyncResponse.thenApply(HttpResponse::body).get(5, TimeUnit.SECONDS);
            crunchifyAsyncResultStatusCode = crunchifyAsyncResponse.thenApply(HttpResponse::statusCode).get(5, TimeUnit.SECONDS);

        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }

        crunnchifyPrint("=============== AsyncHTTPClient Body:===============  \n" + crunchifyAsyncResultBody);
        crunnchifyPrint("\n=============== AsyncHTTPClient Status Code:===============  \n" + crunchifyAsyncResultStatusCode);

    }

    private static void crunnchifyPrint(Object data) {
        System.out.println(data);

    }

}

Simply run above program and you will see below result.

Java Async HttpClient tutorial

IntelliJ IDEA Result:

=============== AsyncHTTPClient Body:===============  
<!DOCTYPE html>
<html>
<body>

<h1>Hey.. This is Crunchify's Java HTTPClient Tutorial. </h1>
<br>Tutorial link: <a href="https://crunchify.me/330iPK7">https://crunchify.me/330iPK7</a>
</body>
</html>

=============== AsyncHTTPClient Status Code:===============  
200

Process finished with exit code 0

What’s next?

Java14 Synchronous HttpClient Example – Overview and Simple Tutorial

The post Java Asynchronous HttpClient Overview and Tutorial – sendAsync() appeared first on Crunchify.