Java : HttpClient with Examples

HttpClient (Java SE 21 & JDK 21) with Examples.
You will find code examples on most HttpClient methods.


Summary

An HTTP Client.

Class diagram

Note: Code examples on this page may use JDK's Simple Web Server (jwebserver), Apache HTTP Server, etc.

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe -o verbose
//Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::".
//Serving R:\java-work and subdirectories on 127.0.0.1 port 8000
//URL http://127.0.0.1:8000/

final var uri = URI.create("http://127.0.0.1:8000/");
System.out.println(uri); // http://127.0.0.1:8000/

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
    System.out.println(response.body()); // abcd
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe -o verbose
// ...
//127.0.0.1 - - [30/Mar/2024:15:09:08 +0900] "GET / HTTP/1.1" 200 -
//Resource requested: R:\java-work
//> Connection: Upgrade, HTTP2-Settings
//> Http2-settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
//> Host: 127.0.0.1:8000
//> Upgrade: h2c
//> User-agent: Java-http-client/21.0.1
//>
//< Date: Sat, 30 Mar 2024 06:09:08 GMT
//< Last-modified: Sat, 30 Mar 2024 05:30:53 GMT
//< Content-type: text/html
//< Content-length: 4
//<
// An asynchronous example
final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder(uri).build();

try (final var client = HttpClient.newHttpClient()) {

    System.out.println("-- sendAsync start --");

    final var future = client.sendAsync(
                    request, HttpResponse.BodyHandlers.ofString())
            .thenApply(response -> {
                System.out.println("thenApply");
                System.out.println("  status code : " + response.statusCode());
                return response.body();
            })
            .thenAccept(body -> {
                System.out.println("thenAccept");
                System.out.println("  body : " + body);
            });

    System.out.println("-- sendAsync sending ...");

    future.join();

    System.out.println("-- end --");
}

// Result
// ↓
//-- sendAsync start --
//-- sendAsync sending ...
//thenApply
//  status code : 200
//thenAccept
//  body : abcd
//-- end --

Constructors

HttpClient ()

Creates an HttpClient.

It's protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.

Methods

abstract Optional<Authenticator> authenticator ()

Returns an Optional containing the Authenticator set on this client.

This code examples use Apache HTTP Server as the test server. Prepare user=abcd, password=XYZ for basic authentication. The code examples use HTTP on the test server, but HTTPS is usually better.

xxxx@xxxx:/var/www/html/auth-test# cat index.html
Auth OK!

xxxx@xxxx:/var/www/html/auth-test# cat .htaccess
AuthType Basic
AuthName "Restricted Files"
AuthUserFile /var/www/test/.htpasswd
Require valid-user

xxxx@xxxx:/var/www/html/auth-test# cat /var/www/test/.htpasswd
abcd:DkUltt9UxTbcs
(user = abcd, password = XYZ)

An example of successful authentication.

final var authenticator = new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("abcd", "XYZ".toCharArray());
    }
};

final var uri = URI.create("http://192.168.1.9/auth-test/index.html");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://192.168.1.9/auth-test/index.html GET

try (final var client = HttpClient.newBuilder()
        .authenticator(authenticator)
        .build()) {

    client.authenticator().ifPresent(a -> {
        System.out.println(a == authenticator); // true
    });

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET http://192.168.1.9/auth-test/index.html) 200
    System.out.println(response.body()); // Auth OK!
}

An example of authentication failure.

final var uri = URI.create("http://192.168.1.9/auth-test/index.html");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://192.168.1.9/auth-test/index.html GET

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET http://192.168.1.9/auth-test/index.html) 401
    System.out.println(response.statusCode()); // 401
}

boolean awaitTermination (Duration duration)

Blocks until all operations have completed execution after a shutdown request, or the duration elapses, or the current thread is interrupted, whichever happens first.

This code examples use node.js as the test server.

// server.js

const http = require('http');
const server = http.createServer((req, res) => {

  console.log('sleep 5 seconds ...');

  setTimeout(() => {
    console.log('end');
    res.end();
  }, 5000);

});

server.listen(8001);
final var uri = URI.create("http://127.0.0.1:8001/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8001/ GET

final var client = HttpClient.newHttpClient();
try {
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
} finally {
    client.shutdown();
}

System.out.println("-- awaitTermination --");

final var startTime = System.nanoTime();

final var duration = Duration.ofSeconds(3);
final var term = client.awaitTermination(duration);
System.out.println("term : " + term);

final var elapsedSec = (System.nanoTime() - startTime) / 1000000000.0;
System.out.println("elapsed time : " + elapsedSec + " sec.");

System.out.println("isTerminated = " + client.isTerminated());

// Result
// ↓
//-- awaitTermination --
//term : false
//elapsed time : 3.0043146 sec.
//isTerminated = false

// -- node.js --
//$ node server.js
//sleep 5 seconds ...
//end
final var uri = URI.create("http://127.0.0.1:8001/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8001/ GET

final var client = HttpClient.newHttpClient();
try {
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
} finally {
    client.shutdown();
}

System.out.println("-- awaitTermination --");

final var startTime = System.nanoTime();

final var duration = Duration.ofSeconds(10);
final var term = client.awaitTermination(duration);
System.out.println("term : " + term);

final var elapsedSec = (System.nanoTime() - startTime) / 1000000000.0;
System.out.println("elapsed time : " + elapsedSec + " sec.");

System.out.println("isTerminated = " + client.isTerminated());

// Result
// ↓
//-- awaitTermination --
//term : true
//elapsed time : 5.00663 sec.
//isTerminated = true

// -- node.js --
//$ node server.js
//sleep 5 seconds ...
//end

void close ()

Initiates an orderly shutdown in which requests previously submitted to send or sendAsync are run to completion, but no new request will be accepted.

final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
}

// -- jwebserver --
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [30/Mar/2024:18:39:04 +0900] "GET / HTTP/1.1" 200 -

An example without a try-with-resources statement.

final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

final var client = HttpClient.newHttpClient();
try {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
} finally {
    client.close();
}

// -- jwebserver --
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [30/Mar/2024:18:39:04 +0900] "GET / HTTP/1.1" 200 -

abstract Optional<Duration> connectTimeout ()

Returns an Optional containing the connect timeout duration for this client.

// Intentionally use port 8000 for example.com to cause a timeout.
final var uri = URI.create("https://example.com:8000/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com:8000/ GET

try (final var client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5))
        .build()) {

    System.out.println(client.connectTimeout()); // Optional[PT5S]

    final var startTime = System.nanoTime();

    try {
        System.out.println("-- send request --");
        final var response = client.send(
                request, HttpResponse.BodyHandlers.ofString());
    } catch (HttpConnectTimeoutException e) {
        System.out.println(e);

        final var elapsedSec = (System.nanoTime() - startTime) / 1000000000.0;
        System.out.println("timeout : " + elapsedSec + " sec.");
    }
}

// Result
// ↓
//-- send request --
//java.net.http.HttpConnectTimeoutException: HTTP connect timed out
//timeout : 5.0700876 sec.
try (final var client = HttpClient.newHttpClient()) {
    System.out.println(client.connectTimeout()); // Optional.empty
}

abstract Optional<CookieHandler> cookieHandler ()

Returns an Optional containing this client's CookieHandler.

final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder(uri).build();

final var cookieHandler = new CookieHandler() {
    @Override
    public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) {
        System.out.println("-- cookie get --");
        System.out.println("uri : " + uri);
        System.out.println("requestHeaders : " + requestHeaders);
        return Map.of();
    }

    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) {
        System.out.println("-- cookie put --");
        System.out.println("uri : " + uri);

        System.out.println("responseHeaders : ");
        for (final var entry : responseHeaders.entrySet()) {
            System.out.println("  " + entry.getKey() + " : " + entry.getValue());
        }
    }
};

try (final var client = HttpClient.newBuilder()
        .cookieHandler(cookieHandler)
        .build()) {

    client.cookieHandler().ifPresent(handler -> {
        System.out.println("cookieHandler : " + (cookieHandler == handler));
    });

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println("res : " + response);
}

// Result
// ↓
//cookieHandler : true
//-- cookie get --
//uri : http://127.0.0.1:8000/
//requestHeaders : {}
//-- cookie put --
//uri : http://127.0.0.1:8000/
//responseHeaders :
//  content-length : [4]
//  content-type : [text/html]
//  date : [Sat, 30 Mar 2024 06:29:22 GMT]
//  last-modified : [Sat, 30 Mar 2024 05:30:53 GMT]
//res : (GET http://127.0.0.1:8000/) 200

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [31/Mar/2024:16:05:09 +0900] "GET / HTTP/1.1" 200 -
try (final var client = HttpClient.newHttpClient()) {
    System.out.println(client.cookieHandler()); // Optional.empty
}

abstract Optional<Executor> executor ()

Returns an Optional containing this client's Executor.

final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder(uri).build();

try (final var executor = Executors.newSingleThreadExecutor();
     final var client = HttpClient.newBuilder().executor(executor).build()) {

    client.executor().ifPresent(e -> {
        System.out.println("executor : " + (e == executor));
    });

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println("res : " + response);
}

// Result
// ↓
//executor : true
//res : (GET http://127.0.0.1:8000/) 200

// -- jwebserver --
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [30/Mar/2024:15:38:41 +0900] "GET / HTTP/1.1" 200 -
try (final var client = HttpClient.newHttpClient()) {
    System.out.println(client.executor()); // Optional.empty
}

abstract HttpClient.Redirect followRedirects ()

Returns the follow redirects policy for this client.

This code examples use Apache HTTP Server as the test server for redirect. Accessing http://192.168.1.9/redirect-test/src.html redirects to https://example.com/ .

xxxx@xxxx:/var/www/html/redirect-test$ cat .htaccess
RewriteEngine on
RewriteRule ^src.html$ https://example.com/ [L,R=301]
final var uri = URI.create("http://192.168.1.9/redirect-test/src.html");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://192.168.1.9/redirect-test/src.html GET

try (final var client = HttpClient.newBuilder()
        .followRedirects(HttpClient.Redirect.NORMAL)
        .build()) {
    System.out.println(client.followRedirects()); // NORMAL

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET https://example.com/) 200

    // Optional[(GET http://192.168.1.9/redirect-test/src.html) 301]
    System.out.println(response.previousResponse());
}
final var uri = URI.create("http://192.168.1.9/redirect-test/src.html");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://192.168.1.9/redirect-test/src.html GET

try (final var client = HttpClient.newHttpClient()) {
    System.out.println(client.followRedirects()); // NEVER

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET http://192.168.1.9/redirect-test/src.html) 301
}

boolean isTerminated ()

Returns true if all operations have completed following a shutdown.

This code examples use node.js as the test server.

// server.js

const http = require('http');
const server = http.createServer((req, res) => {

  console.log('sleep 5 seconds ...');

  setTimeout(() => {
    console.log('end');
    res.end();
  }, 5000);

});

server.listen(8001);
final var uri = URI.create("http://127.0.0.1:8001/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8001/ GET

final var client = HttpClient.newHttpClient();
try {
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
} finally {
    client.shutdown();
}

System.out.println("-- awaitTermination --");

final var startTime = System.nanoTime();

final var duration = Duration.ofSeconds(3);
final var term = client.awaitTermination(duration);
System.out.println("term : " + term);

final var elapsedSec = (System.nanoTime() - startTime) / 1000000000.0;
System.out.println("elapsed time : " + elapsedSec + " sec.");

System.out.println("isTerminated = " + client.isTerminated());

// Result
// ↓
//-- awaitTermination --
//term : false
//elapsed time : 3.0043146 sec.
//isTerminated = false

// -- node.js --
//$ node server.js
//sleep 5 seconds ...
//end
final var uri = URI.create("http://127.0.0.1:8001/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8001/ GET

final var client = HttpClient.newHttpClient();
try {
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
} finally {
    client.shutdown();
}

System.out.println("-- awaitTermination --");

final var startTime = System.nanoTime();

final var duration = Duration.ofSeconds(10);
final var term = client.awaitTermination(duration);
System.out.println("term : " + term);

final var elapsedSec = (System.nanoTime() - startTime) / 1000000000.0;
System.out.println("elapsed time : " + elapsedSec + " sec.");

System.out.println("isTerminated = " + client.isTerminated());

// Result
// ↓
//-- awaitTermination --
//term : true
//elapsed time : 5.00663 sec.
//isTerminated = true

// -- node.js --
//$ node server.js
//sleep 5 seconds ...
//end

static HttpClient.Builder newBuilder ()

Creates a new HttpClient builder.

try (final var client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(15))
        .version(HttpClient.Version.HTTP_1_1)
        .build()) {

    System.out.println(client.connectTimeout()); // Optional[PT15S]
    System.out.println(client.version()); // HTTP_1_1

    final var uri = URI.create("http://127.0.0.1:8000/");
    final var request = HttpRequest.newBuilder(uri).build();

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
}

// -- jwebserver --
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [30/Mar/2024:15:41:22 +0900] "GET / HTTP/1.1" 200 -
try (final var client = HttpClient.newHttpClient()) {

    System.out.println(client.connectTimeout()); // Optional.empty
    System.out.println(client.version()); // HTTP_2

    final var uri = URI.create("http://127.0.0.1:8000/");
    final var request = HttpRequest.newBuilder(uri).build();

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
}

// -- jwebserver --
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [30/Mar/2024:15:41:22 +0900] "GET / HTTP/1.1" 200 -

static HttpClient newHttpClient ()

Returns a new HttpClient with default settings.

try (final var client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(15))
        .version(HttpClient.Version.HTTP_1_1)
        .build()) {

    System.out.println(client.connectTimeout()); // Optional[PT15S]
    System.out.println(client.version()); // HTTP_1_1

    final var uri = URI.create("http://127.0.0.1:8000/");
    final var request = HttpRequest.newBuilder(uri).build();

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
}

// -- jwebserver --
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [30/Mar/2024:15:41:22 +0900] "GET / HTTP/1.1" 200 -
try (final var client = HttpClient.newHttpClient()) {

    System.out.println(client.connectTimeout()); // Optional.empty
    System.out.println(client.version()); // HTTP_2

    final var uri = URI.create("http://127.0.0.1:8000/");
    final var request = HttpRequest.newBuilder(uri).build();

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
}

// -- jwebserver --
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [30/Mar/2024:15:41:22 +0900] "GET / HTTP/1.1" 200 -

WebSocket.Builder newWebSocketBuilder ()

Creates a new WebSocket builder (optional operation).

This code examples use wscat for WebSocket.
https://github.com/websockets/wscat

try (final var client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5))
        .build()) {

    final var uri = URI.create("ws://127.0.0.1:3000/");
    final var data = "abcd";

    final var future = client.newWebSocketBuilder()
            .buildAsync(uri, new WebSocket.Listener() {
                @Override
                public void onOpen(WebSocket webSocket) {
                    System.out.println("-- onOpen --");
                }
            })
            .thenCompose(ws -> {
                System.out.println("sendText : " + data);
                return ws.sendText(data, true);
            })
            .thenCompose(ws -> {
                System.out.println("sendClose");
                return ws.sendClose(WebSocket.NORMAL_CLOSURE, "ok");
            })
            .thenRun(() -> {
                System.out.println("-- shutdown --");
                client.shutdownNow();
            });

    future.join();
}

// Result
// ↓
//-- onOpen --
//sendText : abcd
//sendClose
//-- shutdown --

// -- wscat --
//$ wscat -l 3000
//> abcd

abstract Optional<ProxySelector> proxy ()

Returns an Optional containing the ProxySelector supplied to this client.

final var uri = URI.create("http://127.0.0.1:8000/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

final var proxy = ProxySelector.getDefault();

try (final var client = HttpClient.newBuilder()
        .proxy(proxy)
        .build()) {

    client.proxy().ifPresent(p -> {
        System.out.println(p == proxy); // true
    });

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
}

// -- jwebserver --
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [30/Mar/2024:16:13:58 +0900] "GET / HTTP/1.1" 200 -
try (final var client = HttpClient.newHttpClient()) {
    System.out.println(client.proxy()); // Optional.empty
}

abstract <T> HttpResponse<T> send (HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)

Sends the given request using this client, blocking if necessary to get the response.

// An example of getting the result as a string.
final var uri = URI.create("http://127.0.0.1:8000/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
    System.out.println(response.body()); // abcd
}

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [31/Mar/2024:16:06:04 +0900] "GET / HTTP/1.1" 200 -
// An example of writing the result as a file.
final var file = Path.of("R:", "java-work", "save.txt");
System.out.println(file); // R:\java-work\save.txt

System.out.println(Files.notExists(file)); // true

final var uri = URI.create("http://127.0.0.1:8000/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8000/ GET

try (final var client = HttpClient.newHttpClient()) {
    final var response = client.send(
            request, HttpResponse.BodyHandlers.ofFile(file));

    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
}

System.out.println(Files.readString(file)); // abcd

abstract <T> CompletableFuture<HttpResponse<T>> sendAsync (HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)

Sends the given request asynchronously using this client with the given response body handler.

final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder(uri).build();

try (final var client = HttpClient.newHttpClient()) {

    System.out.println("-- sendAsync start --");

    final var future = client.sendAsync(
                    request, HttpResponse.BodyHandlers.ofString())
            .thenApply(response -> {
                System.out.println("thenApply");
                System.out.println("  status code : " + response.statusCode());
                return response.body();
            })
            .thenAccept(body -> {
                System.out.println("thenAccept");
                System.out.println("  body : " + body);
            });

    System.out.println("-- sendAsync sending ...");

    future.get();

    System.out.println("-- end --");
}

// Result
// ↓
//-- sendAsync start --
//-- sendAsync sending ...
//thenApply
//  status code : 200
//thenAccept
//  body : abcd
//-- end --

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [31/Mar/2024:16:06:53 +0900] "GET / HTTP/1.1" 200 -

abstract <T> CompletableFuture<HttpResponse<T>> sendAsync (HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler, HttpResponse.PushPromiseHandler<T> pushPromiseHandler)

Sends the given request asynchronously using this client with the given response body handler and push promise handler.

Code examples are in preparation.

void shutdown ()

Initiates an orderly shutdown in which requests previously submitted with send or sendAsync are run to completion, but no new request will be accepted.

final var uri = URI.create("http://127.0.0.1:8001/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8001/ GET

final var client = HttpClient.newHttpClient();
try {
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenAccept(res -> {
                System.out.println("-- accept --");
                System.out.println("res : " + res);
            });
} finally {
    System.out.println("-- shutdown --");
    client.shutdown();
}

final var term = client.awaitTermination(Duration.ofSeconds(10));
System.out.println("term : " + term);

// Result
// ↓
//http://127.0.0.1:8001/ GET
//-- shutdown --
//-- accept --
//res : (GET http://127.0.0.1:8001/) 200
//term : true
final var uri = URI.create("http://127.0.0.1:8001/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8001/ GET

final var client = HttpClient.newHttpClient();
try {
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenAccept(res -> {
                System.out.println("-- accept --");
                System.out.println("res : " + res);
            });
} finally {
    System.out.println("-- shutdownNow --");
    client.shutdownNow();
}

final var term = client.awaitTermination(Duration.ofSeconds(10));
System.out.println("term : " + term);

// Result
// ↓
//http://127.0.0.1:8001/ GET
//-- shutdownNow --
//term : true

void shutdownNow ()

This method attempts to initiate an immediate shutdown.

final var uri = URI.create("http://127.0.0.1:8001/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8001/ GET

final var client = HttpClient.newHttpClient();
try {
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenAccept(res -> {
                System.out.println("-- accept --");
                System.out.println("res : " + res);
            });
} finally {
    System.out.println("-- shutdown --");
    client.shutdown();
}

final var term = client.awaitTermination(Duration.ofSeconds(10));
System.out.println("term : " + term);

// Result
// ↓
//http://127.0.0.1:8001/ GET
//-- shutdown --
//-- accept --
//res : (GET http://127.0.0.1:8001/) 200
//term : true
final var uri = URI.create("http://127.0.0.1:8001/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // http://127.0.0.1:8001/ GET

final var client = HttpClient.newHttpClient();
try {
    client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenAccept(res -> {
                System.out.println("-- accept --");
                System.out.println("res : " + res);
            });
} finally {
    System.out.println("-- shutdownNow --");
    client.shutdownNow();
}

final var term = client.awaitTermination(Duration.ofSeconds(10));
System.out.println("term : " + term);

// Result
// ↓
//http://127.0.0.1:8001/ GET
//-- shutdownNow --
//term : true

abstract SSLContext sslContext ()

Returns this client's SSLContext.

final var uri = URI.create("https://example.com/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com/

try (final var client = HttpClient.newHttpClient()) {

    System.out.println(client.sslContext().getProtocol()); // Default

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET https://example.com/) 200
}

abstract SSLParameters sslParameters ()

Returns a copy of this client's SSLParameters.

final var uri = URI.create("https://example.com/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com/ GET

try (final var client = HttpClient.newHttpClient()) {

    final var sslParams = client.sslParameters();
    System.out.println(Arrays.toString(sslParams.getProtocols())); // [TLSv1.3, TLSv1.2]

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET https://example.com/) 200
}

abstract HttpClient.Version version ()

Returns the preferred HTTP protocol version for this client.

final var uri = URI.create("https://example.com/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com/ GET

try (final var client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_1_1)
        .build()) {
    System.out.println(client.version()); // HTTP_1_1

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET https://example.com/) 200
    System.out.println(response.version()); // HTTP_1_1
}
final var uri = URI.create("https://example.com/");

final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com/ GET

try (final var client = HttpClient.newHttpClient()) {
    System.out.println(client.version()); // HTTP_2

    final var response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response); // (GET https://example.com/) 200
    System.out.println(response.version()); // HTTP_2
}

Related posts

To top of page