Advanced level · Module 4: HTTP Clients and JSON in Java · Lesson 2 of 4
Calling APIs with HttpClient
Use java.net.http.HttpClient to send requests, set timeouts and handle responses synchronously and asynchronously.
In this lesson you will
- Build and send requests with HttpClient
- Set connect and request timeouts and check status codes
Key concepts
HttpClientHttpRequest builderBodyHandlers.ofStringtimeout
The lesson
Java 11 and later include HttpClient. Create one client and reuse it: HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();. Build a request with HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(10)).GET().build().
client.send(request, HttpResponse.BodyHandlers.ofString()) returns a response with statusCode() and body(). sendAsync returns a CompletableFuture, so several calls can run at once.
Always set timeouts. Without them, a request over a weak connection can hang for a very long time and freeze the application. Catch IOException and HttpTimeoutException and turn them into clear messages or fallbacks.
Step by step
- Create a shared HttpClient with a connect timeout.
- Send a GET request and print the status code and body.
- Handle a non-200 status with a clear error.
- Switch to sendAsync and call two endpoints in parallel.
Practice activity
Write a WeatherClient (or similar public-API client) with a method that returns the body or throws a descriptive exception for each failure type.
Expected result: The client returns data on success and distinct, readable errors for timeouts, 404 and 5xx responses.
Check your understanding
-
Why should you set request timeouts?
Show answer
So a slow or broken connection cannot block the application indefinitely.
-
What does sendAsync return?
Show answer
A CompletableFuture of the response.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.