Sub topic 1
Calling HTTP APIs with the Java HttpClient
Prerequisites
Assume Java 11 or later, basic HTTP knowledge, and familiarity with checked exceptions and try/catch.
HTTP in brief: requests, responses, methods and status codes
HTTP is a protocol for exchanging messages between a client and a server. A request identifies a resource with a URI, chooses a method, and may include headers and a body. The server returns a response containing a status code, headers, and usually a body.
| Method | Common purpose | Typical success status |
|---|---|---|
| `GET` | Read a resource | `200 OK` |
| `POST` | Create or submit data | `201 Created` |
| `DELETE` | Remove a resource | `204 No Content` |
Status codes in the 2xx range indicate success. 4xx usually means the request is invalid or unauthorized. 5xx indicates a server-side failure. HttpClient does not throw an exception merely because a response has a 404 or 500 status. Your code must inspect the status.
The three core types
HttpClientmanages connections and sends requests.HttpRequestdescribes one outgoing request.HttpResponse<T>contains the status, headers, and a body of typeT.
Building a reusable HttpClient
Create one configured client and reuse it. Reuse allows connection management and supports concurrent calls. Configure policies that should apply to many requests, such as redirects, HTTP version, and the connection timeout.
Building requests: URI, method, headers
A request has its own URI, method, and headers. Request headers describe the data you send or accept. A request timeout limits this particular exchange; it is different from the client's connection timeout.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class SimpleGet {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NORMAL)
.version(HttpClient.Version.HTTP_2)
.build();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10))
.header("Accept", "text/html")
.GET()
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
}
}Choosing a BodyHandler for the response
A BodyHandler determines how Java consumes the response body. Use ofString() for small text or JSON responses, ofByteArray() for small binary data, and ofFile(path) for large downloads. ofLines() processes text as a stream and avoids keeping the complete response in memory.
Exercise
Does a 404 response make HttpClient.send throw an exception?
Show answer
No. The call normally returns an HttpResponse, so inspect response.statusCode(). Network, timeout, and interruption failures are exceptions.