Practice: calling APIs from Java
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Reviewers keep finding the same four slips in HTTP client code. Spotting them fast, and knowing the short fix for each, is what this checkpoint trains.
Mistake 1: a new HttpClient for every call
HttpClient.newHttpClient() inside a method that runs per request builds a fresh client, connection and background thread every time. The code works; it only gets slow as traffic grows.
Example 1 · Mistake: a client per call, and the fix
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.time.Duration;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;
/** PNR status lookups for a train-ticket app; the server counts TCP connections. */class PnrApi { final Set<Integer> connections = ConcurrentHashMap.newKeySet(); HttpServer server;
URI start() throws IOException { server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/pnr/", exchange -> { connections.add(exchange.getRemoteAddress().getPort()); exchange.sendResponseHeaders(204, -1); exchange.close(); }); server.start(); return URI.create("http://127.0.0.1:" + server.getAddress().getPort()); }}
/** Mistake: a new HttpClient inside the method that runs for every lookup. */class WastefulPnrClient { int status(URI base, String pnr) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); return client.send(HttpRequest.newBuilder(base.resolve("/api/v1/pnr/" + pnr)).build(), HttpResponse.BodyHandlers.discarding()).statusCode(); }}
/** Fix: one client, given once through the constructor and shared by every call. */class PnrClient { private final HttpClient client;
PnrClient(HttpClient client) { this.client = client; }
int status(URI base, String pnr) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder(base.resolve("/api/v1/pnr/" + pnr)) .timeout(Duration.ofSeconds(3)) .build(); return client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode(); }}
public class ClientPerCallDemo { public static void main(String[] args) throws IOException, InterruptedException { String[] pnrs = {"4521876390", "4521876391", "4521876392", "4521876393", "4521876394"};
PnrApi api = new PnrApi(); URI base = api.start(); try { WastefulPnrClient wasteful = new WastefulPnrClient(); for (String pnr : pnrs) { wasteful.status(base, pnr); } System.out.println("New client per call: " + pnrs.length + " lookups, " + api.connections.size() + " connections");
api.connections.clear(); PnrClient shared = new PnrClient(HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build()); for (String pnr : pnrs) { shared.status(base, pnr); } System.out.println("One shared client: " + pnrs.length + " lookups, " + api.connections.size() + " connection"); } finally { api.server.stop(0); } }}New client per call: 5 lookups, 5 connections One shared client: 5 lookups, 1 connection
What this code does
WastefulPnrClientbuilds a client insidestatus, so five PNR lookups open five connections.PnrClientreceives one shared client in its constructor and adds a request timeout; the same five lookups reuse one connection.
The fix: build one client at startup (with a connect timeout) and give it to your classes through their constructors. The same goes for the JsonMapper. Both are thread-safe and made to be shared.
Mistake 2: no timeouts
A call with no timeout waits as long as the server takes, and forever if the server hangs. One stuck OTP or payment provider can freeze a screen or use up every thread of a web app.
Example 2 · Mistake: no timeout on a stuck provider, and the fix
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.net.http.HttpTimeoutException;import java.time.Duration;import java.util.concurrent.CompletableFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class NoTimeoutDemo { public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/sms/send-otp", exchange -> { try { Thread.sleep(1500); // the SMS provider is stuck } catch (InterruptedException e) { Thread.currentThread().interrupt(); } exchange.sendResponseHeaders(204, -1); exchange.close(); }); server.start(); URI otp = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/sms/send-otp"); HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build(); try { // Mistake: no request timeout. We watch it from outside for 1 s to show it is still waiting. CompletableFuture<HttpResponse<Void>> waiting = client.sendAsync(HttpRequest.newBuilder(otp).build(), HttpResponse.BodyHandlers.discarding()); try { waiting.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { System.out.println("Without a timeout: still waiting after 1 s, with no limit at all"); } catch (Exception e) { System.out.println("Unexpected: " + e); }
HttpRequest withTimeout = HttpRequest.newBuilder(otp).timeout(Duration.ofMillis(500)).build(); try { client.send(withTimeout, HttpResponse.BodyHandlers.discarding()); } catch (HttpTimeoutException e) { System.out.println("With a 500 ms timeout: " + e.getMessage() + ", show \"Could not send OTP, try again\""); } } finally { server.stop(0); } }}Without a timeout: still waiting after 1 s, with no limit at all With a 500 ms timeout: request timed out, show "Could not send OTP, try again"
What this code does
- The first call has no request timeout. We watch it from outside with
get(1, TimeUnit.SECONDS)only to prove it is still waiting; the call itself has no limit. - The second call sets
timeout(500 ms), sosendthrowsHttpTimeoutExceptionquickly and the app can show a helpful message.
The fix is two settings: connectTimeout on the client and timeout on every request. When a limit is reached you get HttpTimeoutException and can show "Could not send OTP, try again" in a second instead of a frozen page.
Mistake 3: using the body without checking the status
Parsing the body before looking at statusCode() treats an error message as data. With Jackson 3 you can get a record full of nulls, so the screen shows "Rs. null due".
Example 3 · Mistake: an error body mapped as data, and the fix
Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.math.BigDecimal;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;import tools.jackson.databind.json.JsonMapper;
record FeeStatus(String roll, BigDecimal due, String dueDate) {}
record Problem(String title, int status, String detail) {}
public class UncheckedStatusDemo { private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build(); private static final JsonMapper JSON = JsonMapper.builder().build();
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/fees/", exchange -> { byte[] body = "{\"title\":\"Not Found\",\"status\":404,\"detail\":\"No student 21CS999\"}" .getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/problem+json"); exchange.sendResponseHeaders(404, body.length); exchange.getResponseBody().write(body); exchange.close(); }); server.start(); URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/fees/21CS999"); try { HttpResponse<String> response = CLIENT.send( HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(3)).build(), HttpResponse.BodyHandlers.ofString());
// Mistake: map the body without looking at the status. Jackson 3 ignores the unknown // fields of the error body and quietly fills every component with null. FeeStatus wrong = JSON.readValue(response.body(), FeeStatus.class); System.out.println("Unchecked: " + wrong + " -> the screen shows \"Rs. null due\"");
if (response.statusCode() == 200) { System.out.println("Due: " + JSON.readValue(response.body(), FeeStatus.class).due()); } else { Problem problem = JSON.readValue(response.body(), Problem.class); System.out.println("Checked: " + response.statusCode() + " " + problem.detail()); } } finally { server.stop(0); } }}Unchecked: FeeStatus[roll=null, due=null, dueDate=null] -> the screen shows "Rs. null due" Checked: 404 No student 21CS999
What this code does
- The 404 body is a Problem Details object. Mapped as
FeeStatuswithout a status check, Jackson ignores its fields and returns a record ofnulls, with no exception at all. - Checking
statusCode()first sends the error body to theProblemrecord and shows the real reason:No student 21CS999.
The error JSON has none of your record's fields and unknown fields are ignored, so nothing fails at the parse. With plain text you get a NumberFormatException far from the cause.
The fix: read the status first. For 2xx read the data record; for errors read a Problem record (when Content-Type is application/problem+json) and turn it into a clear message or exception.
Mistake 4: swallowed exceptions and unsafe retries
catch (Exception e) { return false; } turns "the service is down" into a wrong answer, such as "you are not eligible for the scholarship". Blind retries are the other side of the same habit.
Example 4 · Mistake: a swallowed exception, and the fix
import java.io.IOException;import java.net.ConnectException;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.time.Duration;
/** Clear failure for callers, with the original exception as the cause. */class ScholarshipApiException extends RuntimeException { ScholarshipApiException(String message, Throwable cause) { super(message, cause); }}
public class SwallowedDemo { private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build(); private static final URI DOWN = URI.create("http://127.0.0.1:1/api/v1/scholarships/21CS042");
/** Mistake: every failure becomes "false", so the student is told they are not eligible. */ static boolean isEligibleSwallowed() { try { HttpResponse<String> r = CLIENT.send(HttpRequest.newBuilder(DOWN).build(), HttpResponse.BodyHandlers.ofString()); return r.body().contains("\"eligible\":true"); } catch (Exception e) { return false; } }
/** Fix: say what really happened, keep the cause, restore the interrupt flag. */ static boolean isEligible() { HttpRequest request = HttpRequest.newBuilder(DOWN).timeout(Duration.ofSeconds(3)).build(); try { HttpResponse<String> r = CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); if (r.statusCode() != 200) { throw new ScholarshipApiException("Scholarship check returned " + r.statusCode(), null); } return r.body().contains("\"eligible\":true"); } catch (ConnectException e) { throw new ScholarshipApiException("Scholarship service at " + DOWN.getHost() + ":" + DOWN.getPort() + " is not reachable", e); } catch (IOException e) { throw new ScholarshipApiException("Scholarship check failed: " + e, e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ScholarshipApiException("Scholarship check was cancelled", e); } }
public static void main(String[] args) { System.out.println("Swallowed: eligible = " + isEligibleSwallowed() + " (wrong, and no clue why)"); try { System.out.println("Eligible: " + isEligible()); } catch (ScholarshipApiException e) { System.out.println("Honest: " + e.getMessage() + " (cause " + e.getCause().getClass().getSimpleName() + ")"); } }}Swallowed: eligible = false (wrong, and no clue why) Honest: Scholarship service at 127.0.0.1:1 is not reachable (cause ConnectException)
What this code does
isEligibleSwallowedturns a refused connection intofalse, a wrong answer that looks real.isEligiblethrowsScholarshipApiExceptionwith a message naming the service and the original exception as its cause, and restores the interrupt flag when cancelled.
e.printStackTrace(); return null; only moves the crash to the next line. Retrying a POST can duplicate orders, retrying a 404 never helps, and retrying with no limit or pause can hammer a server that is already struggling.
The fix: catch specific exceptions, add context and rethrow one clear exception with the cause; restore the interrupt flag; retry only idempotent requests and temporary failures, with a limit and backoff, and use an Idempotency-Key for POSTs.
Finish up
Mark complete & continue
Next: Mini project: exchange-rate client for ShopLite prices