Java : HttpRequest with Examples
HttpRequest (Java SE 21 & JDK 21) with Examples.
You will find code examples on most HttpRequest methods.
Summary
Note: Code examples on this page may use JDK's Simple Web Server (jwebserver), node.js, 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 - - [31/Mar/2024:18:21:21 +0900] "GET / HTTP/1.1" 200 -
//Resource requested: R:\java-work
//> Connection: Upgrade, HTTP2-Settings
//> Http2-settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
//> Host: 127.0.0.1:8000
//> User-agent: Java-http-client/21.0.1
//> Upgrade: h2c
//>
//< Date: Sun, 31 Mar 2024 09:21:21 GMT
//< Last-modified: Sun, 31 Mar 2024 07:01:20 GMT
//< Content-type: text/html
//< Content-length: 4
//<
Constructors
HttpRequest ()
It's protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.
Methods
abstract Optional<HttpRequest.BodyPublisher> bodyPublisher ()
This code examples use node.js as the test server.
// server-post.js
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method == 'POST') {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
console.log('body : ' + body);
res.end();
});
}
});
server.listen(8001);
final var uri = URI.create("http://127.0.0.1:8001/");
final var bodyPublisher = HttpRequest.BodyPublishers.ofString("post text");
final var request = HttpRequest.newBuilder(uri)
.POST(bodyPublisher)
.build();
System.out.println(request); // http://127.0.0.1:8001/ POST
request.bodyPublisher().ifPresent(a -> {
System.out.println(a.equals(bodyPublisher)); // true
});
try (final var client = HttpClient.newHttpClient()) {
final var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response); // (POST http://127.0.0.1:8001/) 200
}
// -- node.js --
//$ node server-post.js
//body : post text
final boolean equals (Object obj)
final var uri = URI.create("https://example.com/");
final var request1 = HttpRequest.newBuilder(uri).build();
final var request2 = HttpRequest.newBuilder(uri).build();
System.out.println(request1); // https://example.com/ GET
System.out.println(request2); // https://example.com/ GET
System.out.println(request1.equals(request2)); // true
final var uri1 = URI.create("https://example.com/");
final var uri2 = URI.create("https://www.example.com/");
final var request1 = HttpRequest.newBuilder(uri1).build();
final var request2 = HttpRequest.newBuilder(uri2).build();
System.out.println(request1); // https://example.com/ GET
System.out.println(request2); // https://www.example.com/ GET
System.out.println(request1.equals(request2)); // false
final var uri = URI.create("https://example.com/");
final var request1 = HttpRequest.newBuilder(uri).GET().build();
final var request2 = HttpRequest.newBuilder(uri).DELETE().build();
System.out.println(request1); // https://example.com/ GET
System.out.println(request2); // https://example.com/ DELETE
System.out.println(request1.equals(request2)); // false
abstract boolean expectContinue ()
final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri)
.expectContinue(true)
.build();
System.out.println(request); // https://example.com/ GET
System.out.println(request.expectContinue()); // true
final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com/ GET
System.out.println(request.expectContinue()); // false
final int hashCode ()
final var uri = URI.create("https://example.com/");
final var request1 = HttpRequest.newBuilder(uri).build();
System.out.println(request1.hashCode()); // 458519378
final var request2 = HttpRequest.newBuilder(uri).DELETE().build();
System.out.println(request2.hashCode()); // -1823680057
final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request.hashCode()); // 951755564
abstract HttpHeaders headers ()
final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri)
.POST(HttpRequest.BodyPublishers.ofString("xyz"))
.header("Content-Type", "text/plain; charset=utf-8")
.header("Content-Language", "en")
.build();
System.out.println(request); // https://example.com/ POST
final var headers = request.headers();
// {Content-Language=[en], Content-Type=[text/plain; charset=utf-8]}
System.out.println(headers.map());
abstract String method ()
final var uri = URI.create("https://example.com/");
final var request1 = HttpRequest.newBuilder(uri).build();
System.out.println(request1); // https://example.com/ GET
System.out.println(request1.method()); // GET
final var request2 = HttpRequest.newBuilder(uri)
.POST(HttpRequest.BodyPublishers.ofString("xyz"))
.build();
System.out.println(request2); // https://example.com/ POST
System.out.println(request2.method()); // POST
final var request3 = HttpRequest.newBuilder(uri).DELETE().build();
System.out.println(request3); // https://example.com/ DELETE
System.out.println(request3.method()); // DELETE
final var request4 = HttpRequest.newBuilder(uri).HEAD().build();
System.out.println(request4); // https://example.com/ HEAD
System.out.println(request4.method()); // HEAD
static HttpRequest.Builder newBuilder ()
final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder().uri(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
}
// -- PowerShell --
//PS R:\java-work> jwebserver.exe
// ...
//127.0.0.1 - - [31/Mar/2024:18:44:07 +0900] "GET / HTTP/1.1" 200
static HttpRequest.Builder newBuilder (HttpRequest request, BiPredicate<String,String> filter)
final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri)
.header("aaa", "xxx")
.header("bbb", "yyy")
.header("ccc", "zzz")
.build();
System.out.println(request); // https://example.com/ GET
System.out.println(request.headers().map()); // {aaa=[xxx], bbb=[yyy], ccc=[zzz]}
final var ret1 = HttpRequest.newBuilder(
request, (name, value) -> true).build();
System.out.println(ret1); // https://example.com/ GET
System.out.println(ret1.headers().map()); // {aaa=[xxx], bbb=[yyy], ccc=[zzz]}
final var ret2 = HttpRequest.newBuilder(
request, (name, value) -> false).build();
System.out.println(ret2); // https://example.com/ GET
System.out.println(ret2.headers().map()); // {}
final var ret3 = HttpRequest.newBuilder(
request, (name, value) -> !name.equals("bbb")).build();
System.out.println(ret3); // https://example.com/ GET
System.out.println(ret3.headers().map()); // {aaa=[xxx], ccc=[zzz]}
static HttpRequest.Builder newBuilder (URI uri)
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:18:45:10 +0900] "GET / HTTP/1.1" 200 -
abstract Optional<Duration> timeout ()
// 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)
.timeout(Duration.ofSeconds(5))
.build();
System.out.println(request); // https://example.com:8000/ GET
System.out.println(request.timeout()); // Optional[PT5S]
final var startTime = System.nanoTime();
try (final var client = HttpClient.newHttpClient()) {
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.0179335 sec.
final var uri = URI.create("http://127.0.0.1:8000/");
final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request.timeout()); // Optional.empty
abstract URI uri ()
final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com/ GET
System.out.println(request.uri()); // https://example.com/
abstract Optional<HttpClient.Version> version ()
final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri).build();
System.out.println(request); // https://example.com/ GET
System.out.println(request.version()); // Optional.empty
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
}
final var uri = URI.create("https://example.com/");
final var request = HttpRequest.newBuilder(uri)
.version(HttpClient.Version.HTTP_1_1)
.build();
System.out.println(request); // https://example.com/ GET
System.out.println(request.version()); // Optional[HTTP_1_1]
try (final var client = HttpClient.newHttpClient()) {
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
}