Java HttpClient Class

HttpClient Class

public static HttpClient new HttpClient()

The HttpClient class is a new HTTP client added in Java 11, and it has the following features.

  • Supports HTTP/2.
  • Supports WebSocket communication, which is lightweight bidirectional communication.
  • Provides asynchronous methods.

Using the HttpClient Class

Below, we will look at communication with HttpClient through an example that retrieves content from a specified URL and prints it.

HttpConnect.java

package com.devkuma.basic.http;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpConnect {
    public static void main(String[] args) throws InterruptedException {
        // 1. Create HttpClient
        HttpClient cli = HttpClient.newBuilder()
                                   .version(HttpClient.Version.HTTP_2)
                                   .build();
        // 2. Create HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                                         .uri(URI.create("https://www.devkuma.com/"))
                                         .build();
        // 3. Send Request
        cli.sendAsync(request, HttpResponse.BodyHandlers.ofString())
           // 4. Receive Response
           .thenAccept(response -> {
               System.out.println(response.body());
           });

        Thread.sleep(3000);
    }
}

Result:

<!doctype html>
<html itemscope itemtype="http://schema.org/WebPage" lang="ko" class="no-js">
  <head>
    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="generator" content="Hugo 0.101.0" />
<meta name="robots" content="index, follow">

...omitted...

1. Creating an HttpClient Object

The HttpClient class manages HTTP communication itself. To create an HttpClient object, first create an HttpClient.Builder object, which is a builder for creating HttpClient, with the builder method, and then configure HTTP communication behavior with its setters.

Method Setting
HttpClient.Builder authenticator(Authenticator auth) Authentication code (HTTP authentication)
HttpClient.Builder connectTimeout(Duration duration) Connection timeout
HttpClient.Builder cookieHandler(CookieHandler cookie) Handler for manipulating cookies
HttpClient.Builder followRedirects(HttpClient.Redirect policy) Specifies whether to follow redirects automatically
HttpClient.Builder priority(int priority) HTTP/2 request priority
HttpClient.Builder version(HttpClient.Version version) HTTP version

▲ Main setter methods of the HttpClient.Builder interface

Finally, call the build method to create an HttpClient object based on the previous settings.

2. Creating an HttpRequest Object

The HttpRequest class manages HTTP requests. After creating a builder (HttpRequest.Builder) with the builder method, set request information with setters and create an HttpRequest object with the build method. This flow is the same as with HttpClient.

The main setters of the HttpRequest.Builder class are summarized below.

Method Setting
HttpRequest.Builder DELETE() Request method (DELETE)
HttpRequest.Builder GET() Request method (GET)
HttpRequest.Builder POST(HttpRequest.BodyPublisher pub) Request method (POST)
HttpRequest.Builder PUT(HttpRequest.BodyPublisher pub) Request method (PUT)
HttpRequest.Builder method(String method, HttpRequest.BodyPublisher body) Request method and request body
HttpRequest.Builder setHeader(String name, String value) Request header
HttpRequest.Builder timeout(Duration duration) Request timeout
HttpRequest.Builder uri(URI uri) Request URI

▲ Main setter methods of the HttpRequest.Builder class

3. Sending the Request

After creating HttpClient and HttpRequest, send the request with the sendAsync method.

sendAsync method

public abstract <T> CompletableFuture<HttpResponse<T>> sendAsync(
    HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)
  T: response body type
  request: request information
  responseBodyHandler: handler for the response body

The responseBodyHandler argument is a handler that processes the response. It can be created with static methods of the HttpResponse.BodyHandlers class.

Method Response body type
HttpResponse.BodyHandler<String> ofString([Charset charset]) String
HttpResponse.BodyHandler<Stream<String>> ofLines() Stream
HttpResponse.BodyHandler<Path> ofFile(Path file [,OpenOption... openOptions]) File
HttpResponse.BodyHandler<InputStream> ofInputStream() Input stream
HttpResponse.BodyHandler<byte[]> ofByteArray() Byte array

▲ Main static methods of the HttpResponse.BodyHandlers class

In this example, the response body is retrieved as a string with the ofString method.

4. Receiving the Response

The thenAccept method handles the result of the request made by the sendAsync method. It receives an HttpResponse object (response) through the lambda expression argument. Here, it returns the body with the body method and prints it.

The main methods of the HttpResponse object are summarized below.

Method Return value
T body() Body
HttpHeaders headers() Response headers
int statusCode() Status code
URI uri() URI

▲ Main getters of the HttpResponse class