The HTTP server

The JDK has an HTTP server in the module jdk.httpserver, and a service of four routes needs nothing else. This page wraps the routing function in a HttpServer, turns a reply into bytes and back, and asks it four questions from the same program. The port is 8091, because 8080 belongs to capstone 3 and the two services should be able to run at once.

The server

HttpServer.create takes an address and a backlog, a context takes a path prefix and a handler, and start begins to accept. One context for "/" catches every path, which is right for a service whose routing is a function: the prefix would only duplicate the function.

package library; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.io.OutputStream; 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.LocalDate; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; public class Desk { record Loan(int id, String member, String title, LocalDate due, LocalDate returned) { State state(LocalDate today) { if (returned != null) { return new Returned(returned); } long days = ChronoUnit.DAYS.between(due, today); if (days > 0) { return new Overdue(days); } if (days >= -2) { return new DueSoon(-days); } return new OnLoan(-days); } String toJson(LocalDate today) { return "{" + field("id", id) + "," + field("member", member) + "," + field("title", title) + "," + field("due", due.toString()) + "," + Q + "state" + Q + ":" + stateJson(state(today)) + "}"; } } sealed interface State permits OnLoan, DueSoon, Overdue, Returned { } record OnLoan(long daysLeft) implements State { } record DueSoon(long daysLeft) implements State { } record Overdue(long daysLate) implements State { } record Returned(LocalDate on) implements State { } static final LocalDate TODAY = LocalDate.of(2026, 11, 20); static final List<Loan> LOANS = List.of( new Loan(1, "Ada", "Dune", LocalDate.of(2026, 11, 25), null), new Loan(2, "Grace", "The Dispossessed", LocalDate.of(2026, 11, 21), null), new Loan(3, "Alan", "Snow Crash", LocalDate.of(2026, 11, 14), null), new Loan(4, "Edsger", "Programming Pearls", LocalDate.of(2026, 11, 10), LocalDate.of(2026, 11, 18))); static final String Q = String.valueOf((char) 34); static final String B = String.valueOf((char) 92); static String field(String name, String value) { return Q + name + Q + ":" + quote(value); } static String field(String name, int value) { return Q + name + Q + ":" + value; } static String quote(String text) { StringBuilder out = new StringBuilder(Q); for (char c : text.toCharArray()) { if (c == 34) { out.append(B).append(Q); } else if (c == 92) { out.append(B).append(B); } else { out.append(c); } } return out.append(Q).toString(); } static String stateJson(State state) { return switch (state) { case OnLoan onLoan -> "{" + field("kind", "on_loan") + "," + field("days", (int) onLoan.daysLeft()) + "}"; case DueSoon dueSoon -> "{" + field("kind", "due_soon") + "," + field("days", (int) dueSoon.daysLeft()) + "}"; case Overdue overdue -> "{" + field("kind", "overdue") + "," + field("days", (int) overdue.daysLate()) + "}"; case Returned returned -> "{" + field("kind", "returned") + "," + field("on", returned.on().toString()) + "}"; }; } static String array(List<Loan> loans, LocalDate today) { StringBuilder out = new StringBuilder("["); for (int i = 0; i < loans.size(); i++) { if (i > 0) { out.append(','); } out.append(loans.get(i).toJson(today)); } return out.append(']').toString(); } record Reply(int status, String body) { } static List<Loan> overdue() { List<Loan> result = new ArrayList<>(); for (Loan loan : LOANS) { if (loan.state(TODAY) instanceof Overdue) { result.add(loan); } } return result; } static Reply route(String path) { if ("/health".equals(path)) { return new Reply(200, "{" + field("status", "ok") + "," + field("loans", LOANS.size()) + "}"); } if ("/loans".equals(path)) { return new Reply(200, array(LOANS, TODAY)); } if ("/loans/overdue".equals(path)) { return new Reply(200, array(overdue(), TODAY)); } if (path.startsWith("/loans/")) { try { int id = Integer.parseInt(path.substring("/loans/".length())); for (Loan loan : LOANS) { if (loan.id() == id) { return new Reply(200, loan.toJson(TODAY)); } } } catch (NumberFormatException e) { return new Reply(400, "{" + field("error", "bad id") + "}"); } return new Reply(404, "{" + field("error", "no such loan") + "}"); } return new Reply(404, "{" + field("error", "no route") + "}"); } static HttpServer start(int port) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", Desk::handle); server.start(); return server; } static void handle(HttpExchange exchange) throws IOException { Reply reply = route(exchange.getRequestURI().getPath()); send(exchange, reply.status(), reply.body()); } static void send(HttpExchange exchange, int status, String body) throws IOException { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8"); exchange.sendResponseHeaders(status, bytes.length); try (OutputStream out = exchange.getResponseBody()) { out.write(bytes); } } public static void main(String[] args) throws Exception { if (args.length > 0 && "serve".equals(args[0])) { HttpServer server = start(8091); System.out.println("listening on " + server.getAddress().getPort()); new java.util.concurrent.CountDownLatch(1).await(); return; } HttpServer server = start(8091); System.out.println("listening on " + server.getAddress().getPort()); try (HttpClient client = HttpClient.newHttpClient()) { for (String path : List.of("/health", "/loans/2", "/loans/overdue", "/loans/9")) { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + path)) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("GET " + path + " -> " + response.statusCode() + " " + response.body()); } } server.stop(0); System.out.println("stopped"); } }

The handler

A handler is a void handle(HttpExchange): it reads the request from the exchange and writes the response into it. The one here is three lines, because the routing function already decided the status and the body. That is the whole benefit of the previous page: the socket code has no if in it.

The bytes and the length

sendResponseHeaders takes the status and the number of bytes, not the number of characters, so the body is converted with StandardCharsets.UTF_8 first. The content type names the same charset, which is how the client knows how to decode the body. The stream is closed with try-with-resources: the server sends the response when the stream closes, and a handler that forgets it hangs the client.

The self test

The main starts the server, calls four paths with java.net.http.HttpClient and stops the server. The client is in try-with-resources because Java 21 made it closeable; closing it waits for the exchanges to finish. The test is not a substitute for the JUnit tests of the next page, and it is the demonstration a reader can run with one command.

The serve mode

With the word serve the program starts the server and waits on a latch that nothing counts down, which is the shortest way to say "run until the process is killed". That mode is what the container of the last page starts; the self test is what a person runs by hand. Both share the same start method.

The run

One command compiles the file and one runs it. The first line is the server's own output, the next four are the replies, and the last says that the server stopped:

javac -Xlint:all -d out src/library/Desk.java
java -cp out library.Desk

listening on 8091
GET /health -> 200 {"status":"ok","loans":4}
GET /loans/2 -> 200 {"id":2,"member":"Grace","title":"The Dispossessed","due":"2026-11-21","state":{"kind":"due_soon","days":1}}
GET /loans/overdue -> 200 [{"id":3,"member":"Alan","title":"Snow Crash","due":"2026-11-14","state":{"kind":"overdue","days":6}}]
GET /loans/9 -> 404 {"error":"no such loan"}
stopped

The next page

The next page tests all of it with JUnit: the model, the two escapes, the routes and one real request over a socket on a port the operating system picks. The Java course covers the server in lesson 134 and the HTTP client in lesson 121.

The code on this page was compiled with OpenJDK 21.0.13 (javac) and run on Alpine Linux in a Docker container. The output is the same on every run: the date is fixed and the port is constant.

Article author: Arthur Isaev