New features of JDK11: new HTTP API

Keywords: Programming Java Mac OS X Apache

brief introduction

Before JDK11, the HTTP function of java was very weak, only HttpURLConnection was provided for HTTP connection, and it was very complex to use. So we usually use the third-party HTTP client (Apache HttpComponents or OkHttp) to make HTTP requests.

Everything has changed in JDK11. In the package, the latest HttpClient, HttpRequest and HttpResponse can fully meet your needs.

More at

Basic process of using HTTP Client request

Usually we need to make an HTTP request in the code, which usually has three steps.

  1. Build an HTTP client.
  2. Generate an HTTP Request.
  3. Use HTTP Client to send HTTP Request to get an HTTP Response.

Create HTTP Client

To make an HTTP request, you need to establish a connection between the HTTP client and the HTTP server. The HTTP protocol is very complex and has many controllable parameters. Therefore, an HttpClient is needed for configuration.

        HttpClient client = HttpClient.newBuilder()

It's easy to create HttpClient, just use newBuilder. We can specify version,connectTimeout,proxy,SSL, authentication or cookie, etc.

Create HTTP Request

Similarly, HttpRequest.newBuilder() can be used to create HTTP requests.

HttpRequest getRequest = HttpRequest.newBuilder()
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36")

In the above example, we created a get request and set the url and head of the request.

If it is a post request, you need to build a request body:

HttpRequest.BodyPublisher requestBody = HttpRequest.BodyPublishers
                .ofString("{ I am body }");
        HttpRequest postRequest = HttpRequest.newBuilder()

Send HTTP request

With client and request, we can send HTTP requests.

HttpResponse<String> response = client.send( getRequest, HttpResponse.BodyHandlers.ofString());
        String respnseBody = response.body();;

This completes a perfect HTTP request.

Asynchronous HTTP request

In the above example, we use client.send to send http request, which is actually synchronous, which means our program must wait until the request result is returned.

HttpClient also provides a method for asynchronous execution of sendAsync. This method returns a completable future.

Let's take another example:

    public void useAsyncHttp()  {
        HttpClient client = HttpClient.newBuilder()

        CompletableFuture<Void> completableFuture=checkUri(client,URI.create(""));
        //Get the value of completabilefuture

    private CompletableFuture<Void> checkUri(HttpClient httpClient, URI uri){
        HttpRequest request = HttpRequest.newBuilder()
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36")

        return httpClient.sendAsync(request,HttpResponse.BodyHandlers.ofString())
                .thenApply(statusCode -> statusCode == 200 )
                .exceptionally(ex -> false)
                .thenAccept(valid ->
                    if (valid) {
              "uri {} is valid",uri);
                    } else {
              "uri {} is not valid", uri);

In the above example, we get the HTTP request, then call the thenApply and thenAccept of CompletableFuture to filter and process the results.

Completable Future is a mixture of Future and CompletionStage. Everyone is familiar with Future. You can get asynchronous execution results through get method. The CompletionStage represents a stage of asynchronous computing. Different stages can depend on each other to form a cascade operation through the then * * method. Similar to the Stream operation, like promise then in ES6, using CompletionStage can avoid callback to hell. CompletionStage can convert asynchronous callbacks into cascading operations.

For more information on completable future, please refer to All about completable future, this article is enough

The parameter of thenApply is a Function, and thenAccept is a Consumer.

Finally, we need to call completabilefuture. Join() to ensure that the asynchronous operation of completabilefuture is completed.

Of course, it is also possible to call the completabilefuture. Get() method.


This article explains the newly created HTTP Client operation of JDK12, and further discusses the use of completable future.

Examples of this article learn-java-base-9-to-20

Author of this article: the flydean program

Link to this article:

Source: flydean's blog

Welcome to my official account: the procedures, the more wonderful things waiting for you!

Posted by PhilipXVIII18 on Wed, 13 May 2020 15:58:37 -0700