Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 11 / Topic 9 of 10

Putting it together: a weather lookup over HTTP(S)

Real-world example: a weather lookup that calls a REST endpoint, reads JSON, and turns a bad response into one clear, custom exception — sections 3, 4, 5/6 and 1, all in one small program. A real weather API lives on the public internet over HTTPS; this course's version talks to the same kind of local HttpServer from section 3, so the lesson's output never depends on the actual weather, or on the internet being reachable at all. Calling a real HTTPS endpoint from your own machine later is the identical code with a different URI.

static String lookupWeather(HttpClient client, URI base, String city) {
    HttpRequest request = HttpRequest.newBuilder(base.resolve("/weather?city=" + city)).GET().build();
    HttpResponse<String> response;
    try {
        response = client.send(request, HttpResponse.BodyHandlers.ofString());
    } catch (IOException | InterruptedException e) {
        throw new WeatherLookupException("could not reach the weather service for " + city + ": " + e.getMessage());
    }
    if (response.statusCode() != 200) {
        throw new WeatherLookupException("weather service returned " + response.statusCode() + " for " + city + ": " + response.body());
    }
    Map<String, String> fields = parseFlatJson(response.body());
    return city + ": " + fields.get("tempC") + "C, " + fields.get("condition");
}
$ javac WeatherLookupDemo.java
$ java WeatherLookupDemo
Pune: 29.5C, Sunny
Mumbai: 31.0C, Humid
Lookup failed: weather service returned 404 for Jaipur: {"error":"unknown city Jaipur"}

WeatherLookupException is unchecked (section 1's rule): a scheduled job calling this for fifty cities should not be forced to wrap every single call in a try/catch just to satisfy the compiler, but it absolutely needs a clear message when one city's lookup fails, which is exactly what you see for Jaipur — a 404 with the server's own error body folded straight into the message, instead of a NullPointerException three lines later from calling .get("tempC") on fields that were never there.

Full program: examples/WeatherLookupDemo.java.

Done here? The practice set for Part 11 — including the solutions — is on the part page.

Search the guide