Sometimes the problem is not your request but the server. A status in the 500s, like 500 Internal Server Error, means your request was fine but the server failed while answering it: a bug, a database that is down, too much traffic. It isn't your fault, and the same request may work a minute later.
Worse than a 500 is no answer at all. By default client.send waits as long as the server takes. Add .timeout(Duration.ofSeconds(…)) to the request to set a limit: when it runs out, client.send throws an HttpTimeoutException. Catch it with try and catch, so your program carries on instead of crashing:
try {
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/weather"))
.timeout(Duration.ofSeconds(5)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Weather: " + response.body());
} catch (HttpTimeoutException e) {
System.out.println("No weather today");
}
The supplier has a route for each problem: /broken always fails, and /slow takes 2 seconds to answer.
GET /broken → 500 {"error": "The supplier is down"}
GET /slow (1-second timeout) → no answer after 1 second: HttpTimeoutException
Your program must print:
/broken: 500 The supplier failed: The supplier is down /slow: no answer after 1 second
Your task: get /broken and print its status, and for any status of 500 or more, the error from its JSON body. Then get /slow with a 1-second timeout inside a try block: print its status if it answers in time, and a message if it times out.
Assignment
Follow the Coding Tutorial to handle a server error and a timeout without crashing.
Hintresponse.statusCode() >= 500 catches every server error at once. Inside the try block, the lines after client.send run only when an answer came in time.
Free plan: 30 tutor messages. PRO is unlimited.
