Stage 6 · Lesson 4 of 8
Calling a public API with HttpClient
Java includes an client in java.net.http. Build one HttpClient and reuse it. Create a request with HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(10)).GET().build(), and send it with client.send(request, HttpResponse.BodyHandlers.ofString()).
Check response.statusCode() before from the body with your JSON library. 200 means success, 401 a bad key, 404 a wrong URL and 429 too many requests. send IOException and InterruptedException, which are checked , so you must handle them.
Encode with URLEncoder, so spaces and symbols are safe in a URL. Wrap the calls in one class that returns your own records or throws a clear exception, so the rest of the program never sees HTTP.
A question to check yourself, an AI practice session and 3 cheat sheet entries come when you add the roadmap to your account. Add it
Resources for this stage
Start with
- GitHub repoFreeProject Based Learning
Community maintained · Beginner
Follow one guided build in your language, then build your own without a guide
Keep handy
Also worth your time
How to present each project: the problem, stack, challenges and results
- Build Your Own XGo deeper
When you want a harder build: a shell, a key-value store or a tiny Git, from scratch