Programming foundations

Stage 6 · Lesson 4 of 8

Calling a public API with HttpClient

Build and ship your first projects

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 repoFree
    Project Based Learning

    Community maintained · Beginner

    Follow one guided build in your language, then build your own without a guide

Keep handy

  • Free APIs that give a small project real data to work with

Also worth your time

Mark this stage as not done?