Lab 11: HTTP Client & REST

Objective

Use Java 11+'s built-in java.net.http.HttpClient to build, send, and handle HTTP requests: GET/POST with headers, async CompletableFuture parallel requests, retry-with-backoff, JSON parsing, and structured response handling.

Background

java.net.http.HttpClient (Java 11+) replaced the old HttpURLConnection with a modern, fluent API supporting HTTP/1.1 and HTTP/2, async operations, and timeouts. HttpRequest and HttpResponse are immutable — requests are built once and can be reused across calls.

Time

25 minutes

Prerequisites

  • Lab 10 (JDBC & SQLite)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: HttpClient config, GET/POST request building, JSON parsing, retry/backoff, parallel async, response handling, Capstone

💡 HttpRequest is immutable and reusable. Build it once, store it, and send it multiple times — the client handles connection pooling automatically. For parallel requests, CompletableFuture-based sendAsync() is far more efficient than spawning threads: it uses non-blocking I/O under the hood so 100 concurrent requests don't need 100 threads.

📸 Verified Output:


Summary

Operation
API

Build client

HttpClient.newBuilder().build()

Build GET

HttpRequest.newBuilder().GET().build()

Build POST

.POST(BodyPublishers.ofString(body))

Send sync

client.send(req, BodyHandlers.ofString())

Send async

client.sendAsync(req, ...)CompletableFuture

Read response

resp.statusCode(), resp.body(), resp.headers()

Further Reading

Last updated