Part 11 / Topic 4 of 10
java.net.http.HttpClient: GET and POST
HttpClient (Java 11+) is the JDK's own HTTP client — no third-party library needed for plain REST calls. The shape is always the same: build a HttpClient once (it's reusable across many requests), build a HttpRequest describing one call, and send() it with a BodyHandler that says how to read the response body.
Think of the client as a courier company you hire once, and each request as one parcel you hand them with an address and instructions — the same courier can carry as many parcels as you give it.
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpRequest request = HttpRequest.newBuilder(base.resolve("/orders/100"))
.timeout(Duration.ofSeconds(5))
.GET() // GET is the default if you omit this
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.headers().firstValue("Content-Type").orElse("?"));
System.out.println(response.body());
A POST sends a body through BodyPublishers, and reads the response the same way:
HttpRequest post = HttpRequest.newBuilder(base.resolve("/orders"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(newOrderJson))
.build();
Running both against a tiny local "orders" API (full server code in the example file):
$ javac HttpClientDemo.java
$ java HttpClientDemo
-- GET an existing order --
status: 200
content-type: application/json
body: {"id":100,"city":"Pune","amount":1200}
-- GET an order that does not exist --
status: 404
body: {"error":"no order 999"}
-- POST a new order --
status: 201
location: /orders/101
body: {"id":101,"city":"Chennai","amount":2550}
Three things to carry forward from this output: statusCode() is a plain int — nothing throws just because the server said 404, so always check it before trusting the body; headers are read with firstValue(name), returning an Optional<String> (Part 9) because a header might not be there at all; and send() itself throws a checked IOException (the network failed) or InterruptedException (the calling thread was interrupted) — both are about the call itself failing, which is a different problem from the server answering with an error status.
⚠️ A
404or500is not a Java exception.send()only throws for a connection-level problem. An error status code is a completely normal, successful HTTP exchange that happens to carry bad news — you check for it the same way you check any other field on the response.
Full program: examples/HttpClientDemo.java.
Done here? The practice set for Part 11 — including the solutions — is on the part page.