Networking
networking5HttpClient
- Path
- pkg10networking/networking5HttpClient.java
- Package
- pkg10networking
- Study order
- 5
- Run
- Single-file source launch
- Command
- java pkg10networking/networking5HttpClient.java
- Dependencies
- com.sun.net.httpserver.HttpServer
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg10networking;2 3import com.sun.net.httpserver.HttpServer;4import java.net.InetSocketAddress;5import java.net.URI;6import java.net.http.HttpClient;7import java.net.http.HttpRequest;8import java.net.http.HttpResponse;9import java.nio.charset.StandardCharsets;10import java.time.Duration;11 12/*13 * networking5HttpClient.java14 * --------------------------15 * The modern HTTP client: java.net.http.HttpClient (Java 11+).16 *17 * DEFINITION:18 * HttpClient is the standard, fluent, HTTP/2-capable client. It supports19 * sync and async calls, timeouts, redirects, and body handlers. This demo20 * talks to a local server so it runs offline.21 *22 * KEY POINTS:23 * - Build once (HttpClient.newBuilder()), reuse for many requests.24 * - HttpRequest is immutable; choose GET/POST and a BodyPublisher.25 * - BodyHandlers.ofString() turns the response body into a String.26 * - sendAsync() returns a CompletableFuture for non-blocking calls.27 */28public class networking5HttpClient {29 30 public static void main(String[] args) throws Exception {31 // Local echo-ish server: GET returns text, POST echoes the request body32 HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);33 server.createContext("/api", ex -> {34 String method = ex.getRequestMethod();35 byte[] reqBody = ex.getRequestBody().readAllBytes();36 String reply = "GET".equals(method)37 ? "{\"message\":\"hello\"}"38 : "{\"echo\":\"" + new String(reqBody, StandardCharsets.UTF_8) + "\"}";39 byte[] out = reply.getBytes(StandardCharsets.UTF_8);40 ex.getResponseHeaders().add("Content-Type", "application/json");41 ex.sendResponseHeaders(200, out.length);42 ex.getResponseBody().write(out);43 ex.close();44 });45 server.start();46 String base = "http://127.0.0.1:" + server.getAddress().getPort() + "/api";47 48 HttpClient client = HttpClient.newBuilder()49 .connectTimeout(Duration.ofSeconds(2))50 .version(HttpClient.Version.HTTP_1_1)51 .build();52 53 // 1) GET54 HttpRequest get = HttpRequest.newBuilder(URI.create(base))55 .header("Accept", "application/json")56 .GET()57 .build();58 HttpResponse<String> getResp = client.send(get, HttpResponse.BodyHandlers.ofString());59 System.out.println("GET status: " + getResp.statusCode());60 System.out.println("GET body : " + getResp.body());61 62 // 2) POST with a body63 HttpRequest post = HttpRequest.newBuilder(URI.create(base))64 .header("Content-Type", "application/json")65 .POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"Ada\"}"))66 .build();67 HttpResponse<String> postResp = client.send(post, HttpResponse.BodyHandlers.ofString());68 System.out.println("\nPOST status: " + postResp.statusCode());69 System.out.println("POST body : " + postResp.body());70 71 // 3) Async GET (non-blocking) — join just to print in this demo72 client.sendAsync(get, HttpResponse.BodyHandlers.ofString())73 .thenApply(HttpResponse::body)74 .thenAccept(b -> System.out.println("\nASYNC body : " + b))75 .join();76 77 server.stop(0);78 }79}