Java : HttpResponse con ejemplos

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

Nota :


Summary

Una respuesta 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.

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> 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/
//127.0.0.1 - - [04/Apr/2024:15:49:13 +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: Thu, 04 Apr 2024 06:49:13 GMT
//< Last-modified: Thu, 4 Apr 2024 06:46:40 GMT
//< Content-type: text/html
//< Content-length: 4
//<

Methods

T body ()

Devuelve el cuerpo. (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 handler = HttpResponse.BodyHandlers.ofString();
    final var response = client.send(request, handler);

    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 - - [04/Apr/2024:15:51:15 +0900] "GET / HTTP/1.1" 200 -
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 handler = HttpResponse.BodyHandlers.ofByteArray();
    final var response = client.send(request, handler);

    System.out.println(response); // (GET http://127.0.0.1:8000/) 200
    System.out.println(Arrays.toString(response.body())); // [97, 98, 99, 100]
}

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:51:15 +0900] "GET / HTTP/1.1" 200 -

HttpHeaders headers ()

Devuelve los encabezados de respuesta recibidos. (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

    System.out.println("-- headers --");
    for (final var header : response.headers().map().entrySet()) {
        System.out.println(header.getKey() + " : " + header.getValue());
    }
}

// Result
// ↓
//-- headers --
//content-length : [4]
//content-type : [text/html]
//date : [Thu, 04 Apr 2024 06:52:27 GMT]
//last-modified : [Thu, 4 Apr 2024 06:46:40 GMT]

// --- PowerShell ---
//PS R:\java-work> cat .\index.html
//abcd
//
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:52:27 +0900] "GET / HTTP/1.1" 200 -

Optional<HttpResponse<T>> previousResponse ()

Devuelve un Opcional que contiene la respuesta intermedia anterior, si se recibió alguna. (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()) {

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

HttpRequest request ()

Devuelve el HttpRequest correspondiente a esta respuesta. (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

    final var ret = response.request();
    System.out.println(ret); // http://127.0.0.1:8000/ GET
    System.out.println(ret.equals(request)); // true
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:57:47 +0900] "GET / HTTP/1.1" 200 -

Optional<SSLSession> sslSession ()

Devuelve un Opcional que contiene la SSLSession vigente para esta respuesta. (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 response = client.send(
            request, HttpResponse.BodyHandlers.ofString());

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

    response.sslSession().ifPresent(ssl -> {
        System.out.println(ssl.getPeerHost()); // example.com
        System.out.println(ssl.getProtocol()); // TLSv1.3
        System.out.println(ssl.getCipherSuite()); // TLS_AES_256_GCM_SHA384
    });
}

int statusCode ()

Devuelve el código de estado de esta respuesta. (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
    System.out.println(response.statusCode()); // 200
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:59:43 +0900] "GET / HTTP/1.1" 200 -
final var uri = URI.create("http://127.0.0.1:8000/");

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

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

    System.out.println(response); // (DELETE http://127.0.0.1:8000/) 405
    System.out.println(response.statusCode()); // 405
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:15:59:43 +0900] "DELETE / HTTP/1.1" 405 -

URI uri ()

Devuelve el URI del que se recibió la respuesta. (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
    System.out.println(response.uri()); // http://127.0.0.1:8000/
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:16:00:32 +0900] "GET / HTTP/1.1" 200 -

HttpClient.Version version ()

Devuelve la versión del protocolo HTTP que se utilizó para esta respuesta. (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()) {
    System.out.println(client.version()); // HTTP_2

    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.version()); // HTTP_1_1
}

// --- PowerShell ---
//PS R:\java-work> jwebserver.exe
//...
//127.0.0.1 - - [04/Apr/2024:16:01:57 +0900] "GET / HTTP/1.1" 200 -
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