Capstone 3: an HTTP service

The third project serves the task list over HTTP. The server is HttpServer from the module jdk.httpserver, which is in the JDK and needs no library; the client of the test is java.net.http.HttpClient, which is also in the JDK. The JSON is written by hand, because a service of four fields does not need a library either.

The server

The server is created with an address and a backlog, given one context per path and started. The contexts are prefixes, so /tasks receives /tasks and /tasks/2 and everything else under it, and a path with no context gets the 404 of the server itself.

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.util.List; public class Service { record Task(int id, String title, boolean done) { String toJson() { return "{\"id\":" + id + ",\"title\":\"" + title + "\",\"done\":" + done + "}"; } } static final List<Task> TASKS = List.of( new Task(1, "write the report", false), new Task(2, "read the spec", true), new Task(3, "answer mail", false)); public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/health", Service::health); server.createContext("/tasks", Service::tasks); server.start(); System.out.println("listening on " + server.getAddress().getPort()); if (args.length > 0 && args[0].equals("serve")) { new java.util.concurrent.CountDownLatch(1).await(); return; } HttpClient client = HttpClient.newHttpClient(); for (String path : new String[] {"/health", "/tasks", "/tasks/2", "/tasks/9"}) { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://127.0.0.1:8080" + 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: " + true); } static void health(HttpExchange exchange) throws IOException { send(exchange, 200, "{\"status\":\"ok\",\"tasks\":" + TASKS.size() + "}"); } static void tasks(HttpExchange exchange) throws IOException { String path = exchange.getRequestURI().getPath(); if (path.equals("/tasks")) { StringBuilder out = new StringBuilder("["); for (int i = 0; i < TASKS.size(); i++) { if (i > 0) { out.append(','); } out.append(TASKS.get(i).toJson()); } send(exchange, 200, out.append(']').toString()); return; } String last = path.substring(path.lastIndexOf('/') + 1); for (Task task : TASKS) { if (String.valueOf(task.id()).equals(last)) { send(exchange, 200, task.toJson()); return; } } send(exchange, 404, "{\"error\":\"no such task\"}"); } 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); } } }

A handler

A handler is a HttpExchange in and nothing out: it reads the request from the exchange and writes the response into it. The page's send is the whole of the writing: the content type, the status and the length, then the bytes into the body stream, which is closed with the try-with-resources of lesson 098.

The length is the number of bytes of the body and not of its characters, which matters as soon as a title has an accent: getBytes with a charset is the same rule as lesson 109. A body written without the length would hang the client, because the server would keep the connection open waiting for more.

JSON by hand

The record's toJson is four fields and no library, and the escaping of lesson 130 is left out on purpose: the titles here are typed by the program and contain no quote. A service that accepts a title from a request needs that escaping, and the honest note is that this one does not parse a request body at all: it serves the three tasks it has.

The array is built with a StringBuilder and a comma between the elements, which is the shape of the writer of lesson 130 without the recursion. A document of one level does not need the switch; a document of any depth does, which is why the writer is the lesson and this is the shortcut.

The self test

The program starts the server and then calls it with a client, so one run shows the server and the four answers. The port is fixed at 8080, and the server prints the number it got, which for a fixed address is the same:

javac -Xlint:all -d out Service.java
java -cp out Service

listening on 8080
GET /health -> 200 {"status":"ok","tasks":3}
GET /tasks -> 200 [{"id":1,"title":"write the report","done":false},{"id":2,"title":"read the spec","done":true},{"id":3,"title":"answer mail","done":false}]
GET /tasks/2 -> 200 {"id":2,"title":"read the spec","done":true}
GET /tasks/9 -> 404 {"error":"no such task"}
stopped: true

Four requests, two statuses. /health is the path a monitor calls, and it answers with the count of tasks; /tasks answers the list; /tasks/2 answers one task because the handler reads the last part of the path; and /tasks/9 answers the 404 of the handler, with a body a client can read.

A path outside the two contexts answers the 404 of the server itself, which is HTML and not JSON: /missing gives <h1>404 Not Found</h1>No context found for request. A service that wants JSON everywhere registers a context for / as well, and the lesson leaves that to the exercise.

A request from another process

A server is meant to be called by somebody else, so the class has a second mode: with the word serve it starts the server and waits on a latch that nothing counts down, instead of testing itself. The latch is the shortest way to say "run until the process is killed", and it is what an entry point of a container does. A second program, Call.java, sends one request to a path it takes from its arguments and prints the status, the content type and the body:

import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class Call { public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("usage: call <path> (the server must be running)"); return; } HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://127.0.0.1:8080" + args[0])) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode() + " " + response.headers().firstValue("content-type").orElse("-")); System.out.println(response.body()); } }

javac -Xlint:all -d out Call.java
java -cp out Service serve > server.log 2>&1 &
SERVER=$!
sleep 1
java -cp out Call /health
java -cp out Call /tasks/3
kill $SERVER

200 application/json; charset=utf-8
{"status":"ok","tasks":3}
200 application/json; charset=utf-8
{"id":3,"title":"answer mail","done":false}

The server writes its one line to server.log, where the file holds listening on 8080, because its output would otherwise interleave with the two replies and the order of the two streams is the shell's. The sleep is the wait for the socket to be open, $! is the pid of the background job, and kill ends the server at the end of the run. The four lines are the two calls from another process, and the content type comes back with the charset the handler set, which is what a client uses to decode the body.

The client is compiled into the same folder as the service, so the two runs share the class path. A tool a person would use for the same two calls is curl, which is not in this image; the class above is the same request with the JDK alone. The The pid is the exact process, so the kill ends this server and no other; a service that is deployed runs until its container is stopped instead.

Exercises

  1. Register a context for / that answers JSON for every path and call it with /missing.
  2. Add a /tasks/count path that answers one number.
  3. Escape the title in toJson with the writer of lesson 130 and serve a title with a quote in it.
  4. Run the server on port 0 and print the port it got, then call it with that port.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which module provides HttpServer?

    Answer

    jdk.httpserver, which is in the JDK

    The class is com.sun.net.httpserver.HttpServer and the module ships with the JDK.

  2. What is a context in this server?

    Answer

    A path prefix and the handler that serves everything under it

    createContext binds a prefix, which is why /tasks receives /tasks/2 as well.

  3. What does sendResponseHeaders(status, length) take as its length?

    Answer

    The number of bytes of the body

    The protocol counts bytes, which is why the body is converted with a charset first.

  4. What does this program print? public class Q1 { public static void main(String[] args) { String body = "{\"ok\":true}"; System.out.println(body.getBytes(java.nio.charset.StandardCharsets.UTF_8).length); System.out.println(body); } }

    Answer

    11 / {"ok":true}

    The eleven ASCII characters are eleven bytes, quotes included.

  5. Why does the handler set the content type?

    Answer

    The client decodes the body by it, and JSON has a type of its own

    A response without a type is a guess for the client, and application/json with a charset is the answer.

  6. What does a path outside every context receive?

    Answer

    The 404 of the server itself, which is HTML and not JSON

    The server answers before a handler is chosen, and its page is HTML.

  7. Why does the program start the server before it starts the client?

    Answer

    A request to a port nobody listens on fails at once

    send on a closed port throws a ConnectException, which the two-process run shows as a rule.

  8. What does this program print? public class Q2 { public static void main(String[] args) { String path = "/tasks/42"; String last = path.substring(path.lastIndexOf("/") + 1); System.out.println(last); System.out.println(last.equals("42")); } }

    Answer

    42 / true

    The substring after the last slash is the id, which the handler compares with each task.

  9. What does HttpClient.send answer?

    Answer

    An HttpResponse with the status, the headers and the body

    The response object carries all three, and the body handler decides how the body arrives.

  10. Why is the JSON written by hand rather than by a library?

    Answer

    The document is four flat fields, and no library is in the image anyway

    The lesson says what the shortcut leaves out: the escaping and the request body.

The modern project group builds another service over the same HttpServer, with the routing in a function and the jar in a Dockerfile: the HTTP server is the long form of this page.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev