This tutorial explains the usage of the Java HttpClient class which was added with Java 11.

1. Introduction to the Java HTTP Client

1.1. Overview

The Java HTTP client added with Java 11 supports HTTP/1.1 and HTTP/2. I uses a builder pattern and allows synchronous and asynchronous programming.

1.2. Create example project

Create a example project called com.vogela.java.httpclient. If you using a module-info.java file, ensure that java.net.http is required.

module com.vogella.java.httpclient {
    requires java.net.http;
}

Create a test class in which your HttpClient code can be placed:

package com.vogella.java.httpclient;

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;


public class ReadWebpage {
    public static void main(String[] args) {
        // Place your HttpClient test code here
    }
}

1.3. Using HttpClient to perform a synchronous GET request

The following example performs a synchronous HTTP Get request and prints the result to the console.

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://www.google.com/")).build();
try {
        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
        if (response.statusCode()==200) {
            System.out.println(response.body());
        }

    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
}

1.4. Using HttpClient to perform a asynchronous GET request

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://www.google.com/")).build();
client.sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

1.5. Providing the authentication for a connection

You can use an Authenticator to provide the credentials for a HttpClient.

HttpClient.newBuilder()
    .authenticator(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                "youruser",
                "yourpassword".toCharArray());
            }
        }).build();

1.6. Error handling in HttpClient

package aero.minova.rcp.dataservice;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;

public class Snippet {

    public static void main(String[] argv) {
        var client = HttpClient.newBuilder().build();
        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://www.vogella.com/"))
                .build();
        CompletableFuture<String> thenApplyAsync = client
                .sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApplyAsync((resp) -> {
                    int status = resp.statusCode();
                    if (status != 200) {
                        System.err.println("Error: " + resp.statusCode());
                        return "NOT VALID";
                    }
                    return resp.body();
                });
        thenApplyAsync.join(); // prevents main() from exiting too early
    }
}