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. Java HttpCLient resources

2. vogella training and consulting support

Copyright © 2012-2019 vogella GmbH. Free use of the software examples is granted under the terms of the Eclipse Public License 2.0. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.