Java : HttpClient con ejemplos

HttpClient (Java SE 21 & JDK 21) en Java con ejemplos.
Encontrará ejemplos de código en la mayoría de los métodos de HttpClient.

Nota :


Summary

Un cliente HTTP. (Traducción automática)

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 ()

Crea un HttpClient. (Traducción automática)

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 ()

Devuelve un Opcional que contiene el Autenticador configurado en este cliente. (Traducción automática)

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)

Se bloquea hasta que todas las operaciones hayan completado su ejecución después de una solicitud de cierre, o transcurra la duración, o se interrumpa el subproceso actual, lo que ocurra primero. (Traducción automática)

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 ()

Inicia un cierre ordenado en el que las solicitudes enviadas previamente para enviar o enviarAsync se ejecutan hasta su finalización, pero no se aceptará ninguna solicitud nueva. (Traducción automática)

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 ()

Devuelve un opcional que contiene la duración del tiempo de espera de conexión para este cliente. (Traducción automática)

// 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 ()

Devuelve un opcional que contiene el CookieHandler de este cliente. (Traducción automática)

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 ()

Devuelve un Opcional que contiene el Ejecutor de este cliente. (Traducción automática)

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 ()

Devuelve la siguiente política de redirecciones para este cliente. (Traducción automática)

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 ()

Devuelve verdadero si todas las operaciones se han completado después de un apagado. (Traducción automática)

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 ()

Crea un nuevo constructor HttpClient. (Traducción automática)

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 ()

Devuelve un nuevo HttpClient con la configuración predeterminada. (Traducción automática)

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 ()

Crea un nuevo constructor WebSocket (operación opcional). (Traducción automática)

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 ()

Devuelve un Opcional que contiene el ProxySelector proporcionado a este cliente. (Traducción automática)

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)

Envía la solicitud dada utilizando este cliente, bloqueándolo si es necesario para obtener la respuesta. (Traducción automática)

// 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)

Envía la solicitud dada de forma asincrónica utilizando este cliente con el controlador del cuerpo de respuesta dado. (Traducción automática)

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)

Envía la solicitud dada de forma asincrónica utilizando este cliente con el controlador del cuerpo de respuesta dado y el controlador de promesa push. (Traducción automática)

Code examples are in preparation.

void shutdown ()

Inicia un cierre ordenado en el que las solicitudes enviadas previamente con send o sendAsync se ejecutan hasta su finalización, pero no se aceptará ninguna nueva solicitud. (Traducción automática)

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 ()

Este método intenta iniciar un apagado inmediato. (Traducción automática)

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 ()

Devuelve el SSLContext de este cliente. (Traducción automática)

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 ()

Devuelve una copia de los SSLParameters de este cliente. (Traducción automática)

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 ()

Devuelve la versión del protocolo HTTP preferida para este cliente. (Traducción automática)

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