A minimal HTTP server
suggest changeThe JDK ships with a small HTTP/1.1 server in the com.sun.net.httpserver package (module jdk.httpserver). Despite the com.sun name it is a supported, public API: it has been in every JDK since Java 6 and is documented alongside java.net.http. It needs no dependencies, starts in milliseconds and is a good fit for:
- small internal tools, admin endpoints, health checks and metrics
- test doubles: a fake REST service that a test starts and stops
- learning how HTTP works without a framework in the way
It is not a replacement for Jetty, Tomcat, Netty or a framework like Spring Boot, Javalin or Helidon. It has no HTTP/2, no WebSockets, no routing beyond path prefixes and no JSON support. The last section lists what's missing.
Every example below is a single file you can run with the source launcher (java Hello.java). Examples that test themselves start the server on a free port (new InetSocketAddress("localhost", 0)) and call it with java.net.http.HttpClient. All output comes from JDK 25.
For a lower-level view of what goes over the wire see Basic Client and Server Communication using a Socket. For headers in depth see HTTP headers.
Hello, world
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
public class Hello {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", exchange -> {
byte[] body = "Hello, world!\n".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
exchange.sendResponseHeaders(200, body.length);
try (var out = exchange.getResponseBody()) {
out.write(body);
}
});
server.start();
System.out.println("Listening on http://localhost:8080/");
}
}
Run it with java Hello.java and it prints Listening on http://localhost:8080/. The program doesn't exit when main returns, because the server runs on its own non-daemon thread. Stop it with Ctrl+C.
$ curl -i http://localhost:8080/
HTTP/1.1 200 OK
Date: Sat, 17 Oct 2026 19:46:46 GMT
Content-type: text/plain; charset=utf-8
Content-length: 14
Hello, world!
The moving parts:
HttpServer.create(address, backlog)binds the socket.new InetSocketAddress(8080)listens on all network interfaces. Usenew InetSocketAddress("localhost", 8080)to accept only local connections. Port0asks the OS for any free port, andserver.getAddress().getPort()tells you which one you got. A backlog of0means "use the system default" for the queue of not yet accepted connections.createContext(path, handler)maps a path prefix to anHttpHandler.HttpHandleris a functional interface with one method,void handle(HttpExchange exchange) throws IOException, so a lambda works.start()starts a background dispatcher thread and returns immediately.
A handler always does the same four steps, in this order:
- read what it needs from the request
- set response headers with
getResponseHeaders() - call
sendResponseHeaders(status, length)exactly once - write the body to
getResponseBody()and close it (or close the exchange)
Headers set after sendResponseHeaders() are silently ignored because they've already been sent. The server doesn't add a Content-Type for you, so set one.
The request: HttpExchange
HttpExchange holds both the request and the response. This handler sends back what it learned about the request:
import com.sun.net.httpserver.HttpExchange;
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.nio.charset.StandardCharsets;
public class Inspect {
static void handle(HttpExchange ex) throws IOException {
String body;
try (var in = ex.getRequestBody()) {
body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
URI uri = ex.getRequestURI();
String report = """
method: %s
context: %s
path: %s
raw query: %s
content-type: %s
body: %s
remote: %s
""".formatted(
ex.getRequestMethod(),
ex.getHttpContext().getPath(),
uri.getPath(),
uri.getRawQuery(),
ex.getRequestHeaders().getFirst("content-type"), // case-insensitive
body,
ex.getRemoteAddress().getAddress().getHostAddress());
byte[] out = report.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
ex.sendResponseHeaders(200, out.length);
try (var os = ex.getResponseBody()) {
os.write(out);
}
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/api", Inspect::handle);
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
HttpClient client = HttpClient.newHttpClient();
HttpRequest get = HttpRequest.newBuilder(
URI.create(base + "/api/users?name=J%C3%B3zef&limit=10")).build();
System.out.println(client.send(get, HttpResponse.BodyHandlers.ofString()).body());
HttpRequest post = HttpRequest.newBuilder(URI.create(base + "/api/users"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"Ann\"}"))
.build();
System.out.print(client.send(post, HttpResponse.BodyHandlers.ofString()).body());
server.stop(0);
}
}
Output:
method: GET
context: /api
path: /api/users
raw query: name=J%C3%B3zef&limit=10
content-type: null
body:
remote: 127.0.0.1
method: POST
context: /api
path: /api/users
raw query: null
content-type: application/json
body: {"name":"Ann"}
remote: 127.0.0.1
Things to notice:
getRequestURI()is the URI from the request line: a path and an optional query. It has no scheme or host. UsegetRawQuery()and decode the parameters yourself (shown later).getQuery()decodes the whole string first, so an encoded&or=in a value becomes impossible to tell apart from a separator.- The context path (
/api) is not stripped from the path. Handlers see the full path. getRequestHeaders()returns aHeadersobject, which is aMap<String, List<String>>with case-insensitive keys.getFirst()returns the first value ornull.- Read the request body before you send the response. If a handler leaves part of the body unread, the server discards up to 64 KB of it when the exchange is closed so the keep-alive connection can be reused. If more is left, it closes the connection.
Response length: Content-Length, chunked or nothing
The second argument of sendResponseHeaders() is easy to get wrong:
length |
Meaning |
|---|---|
> 0 |
Exact body size in bytes. Sent as Content-Length. Writing more or fewer bytes is an error |
0 |
Size unknown. The body is sent with Transfer-Encoding: chunked, write as much as you like |
-1 |
No body at all. Use it for 204 No Content, 304 Not Modified and responses to HEAD |
Note that the length is in bytes, not characters: "zażółć".length() is 6 but its UTF-8 encoding is 10 bytes. Always convert to byte[] first and use the array's length. A raw socket shows the difference on the wire:
import com.sun.net.httpserver.HttpServer;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Lengths {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/fixed", ex -> {
byte[] body = "known size".getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(200, body.length); // > 0: Content-Length
try (OutputStream os = ex.getResponseBody()) {
os.write(body);
}
});
server.createContext("/chunked", ex -> {
ex.sendResponseHeaders(200, 0); // 0: chunked, any length
try (OutputStream os = ex.getResponseBody()) {
os.write("part 1,".getBytes(StandardCharsets.UTF_8));
os.flush();
os.write("part 2".getBytes(StandardCharsets.UTF_8));
}
});
server.createContext("/empty", ex -> {
ex.sendResponseHeaders(204, -1); // -1: no body at all
ex.close();
});
server.start();
int port = server.getAddress().getPort();
for (String path : new String[] {"/fixed", "/chunked", "/empty"}) {
// a raw socket shows exactly what goes over the wire
try (Socket s = new Socket("localhost", port)) {
String req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
s.getOutputStream().write(req.getBytes(StandardCharsets.US_ASCII));
String resp = new String(s.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
System.out.println("--- " + path);
System.out.print(resp.replaceAll("Date: .*\r\n", "").replace("\r\n", "\n"));
System.out.println();
}
}
server.stop(0);
}
}
Output (with the Date header removed):
--- /fixed
HTTP/1.1 200 OK
Content-length: 10
known size
--- /chunked
HTTP/1.1 200 OK
Transfer-encoding: chunked
7
part 1,
6
part 2
0
--- /empty
HTTP/1.1 204 No Content
In the chunked response each chunk is preceded by its size in hex and a zero-size chunk marks the end. Use 0 when you stream data whose size you don't know up front, for example a large file or a CSV export generated row by row.
Contexts and path matching
A context matches by plain string prefix and the longest matching prefix wins. Requests that match no context get a built-in 404 page.
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
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;
public class Contexts {
static HttpHandler reply(String name) {
return ex -> {
byte[] body = (name + " handled " + ex.getRequestURI().getPath())
.getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(200, body.length);
try (var os = ex.getResponseBody()) {
os.write(body);
}
};
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/api", reply("api"));
server.createContext("/api/admin", reply("admin"));
server.createContext("/static/", reply("static"));
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
HttpClient client = HttpClient.newHttpClient();
String[] paths = {"/api", "/api/users/7", "/api/admin/stats", "/apiary",
"/static/app.css", "/static", "/"};
for (String path : paths) {
HttpResponse<String> r = client.send(
HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.ofString());
System.out.printf("%-18s %d %s%n", path, r.statusCode(), r.body());
}
server.stop(0);
}
}
Output:
/api 200 api handled /api
/api/users/7 200 api handled /api/users/7
/api/admin/stats 200 admin handled /api/admin/stats
/apiary 200 api handled /apiary
/static/app.css 200 static handled /static/app.css
/static 404 <h1>404 Not Found</h1>No context found for request
/ 404 <h1>404 Not Found</h1>No context found for request
Two surprises:
/apiaryis handled by the/apicontext. The match is a string prefix, not a path segment prefix. If that matters, register/api/with a trailing slash, or check the path in the handler./static/doesn't match/static, for the same reason.
Contexts don't know about HTTP methods or path parameters such as /users/7. For anything beyond a few fixed paths you write a small router, as in the full example below.
Handling exceptions
When a handler throws, HttpServer closes the connection without sending any response, and by default it logs nothing you'd notice. The client only sees a dropped connection:
import com.sun.net.httpserver.HttpHandler;
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.nio.charset.StandardCharsets;
public class Throws {
// Wraps a handler: an uncaught exception becomes a 500 response
static HttpHandler safe(HttpHandler h) {
return ex -> {
try {
h.handle(ex);
} catch (Exception e) {
System.out.println("server: " + e);
if (ex.getResponseCode() == -1) { // headers not sent yet
byte[] body = "Internal Server Error".getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(500, body.length);
ex.getResponseBody().write(body);
}
} finally {
ex.close();
}
};
}
public static void main(String[] args) throws Exception {
HttpHandler buggy = ex -> {
String query = ex.getRequestURI().getQuery(); // null: no query string
int id = Integer.parseInt(query); // throws
ex.sendResponseHeaders(200, -1);
};
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/raw", buggy);
server.createContext("/safe", safe(buggy));
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
HttpClient client = HttpClient.newHttpClient();
for (String path : new String[] {"/raw", "/safe"}) {
try {
HttpResponse<String> r = client.send(
HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.ofString());
System.out.println(path + " -> " + r.statusCode() + " " + r.body());
} catch (IOException e) {
System.out.println(path + " -> " + e);
}
}
server.stop(0);
}
}
Output:
/raw -> java.io.IOException: HTTP/1.1 header parser received no bytes
server: java.lang.NumberFormatException: Cannot parse null string
/safe -> 500 Internal Server Error
getResponseCode() returns -1 until sendResponseHeaders() has been called, so the wrapper knows whether it can still send a 500. Once headers are out, the only thing left to do is close the exchange.
Note the finally. It's tempting to write try (ex) { ... } catch (Exception e) { ... } since HttpExchange is AutoCloseable, but try-with-resources closes the resource before the catch block runs. The 500 would then be written to an already closed exchange.
Threads and executors
By default, all handlers run on a single thread, the server's dispatcher thread. One slow request blocks everyone else. Give the server an Executor with setExecutor() before start(). Since Java 21, virtual threads are the natural choice: one cheap thread per request, and blocking calls (JDBC, file I/O, outgoing HTTP) are fine.
import com.sun.net.httpserver.HttpServer;
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;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class Threads {
static void run(String label, Executor executor) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/slow", ex -> {
try {
Thread.sleep(200); // simulate a slow database call
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
byte[] body = Thread.currentThread().toString().getBytes(StandardCharsets.UTF_8);
ex.sendResponseHeaders(200, body.length);
try (var os = ex.getResponseBody()) {
os.write(body);
}
});
server.setExecutor(executor); // null = the default
server.start();
URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/slow");
HttpClient client = HttpClient.newHttpClient();
long start = System.nanoTime();
List<CompletableFuture<HttpResponse<String>>> futures = IntStream.range(0, 10)
.mapToObj(i -> client.sendAsync(HttpRequest.newBuilder(uri).build(),
HttpResponse.BodyHandlers.ofString()))
.toList();
String sample = futures.getFirst().join().body();
futures.forEach(CompletableFuture::join);
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("%-16s 10 requests in %4d ms, e.g. %s%n", label, ms, sample);
server.stop(0);
}
public static void main(String[] args) throws Exception {
run("default", null);
run("virtual threads", Executors.newVirtualThreadPerTaskExecutor());
}
}
Output:
default 10 requests in 2174 ms, e.g. Thread[#53,HTTP-Dispatcher,5,main]
virtual threads 10 requests in 213 ms, e.g. VirtualThread[#102]/runnable@ForkJoinPool-1-worker-1
With the default executor the 10 requests are served one after another. With virtual threads they all run at once. A fixed pool such as Executors.newFixedThreadPool(16) also works, and limits how many requests run at the same time.
Once handlers run concurrently, any state they share must be thread-safe: use ConcurrentHashMap, atomics or locks. See Thread-safe Collections.
Serving static files
Java 18 added SimpleFileServer. Its createFileHandler(Path) returns a handler that serves a directory. It handles GET and HEAD, sets Content-Type from the file extension, serves index.html for directories (or a listing if there's none) and refuses paths that escape the root directory. The path must be absolute.
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
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.file.Files;
import java.nio.file.Path;
public class Static {
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("site"); // must be an absolute path
Files.writeString(root.resolve("index.html"), "<h1>Home</h1>\n");
Files.writeString(root.resolve("style.css"), "h1 { color: navy }\n");
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/static", SimpleFileServer.createFileHandler(root));
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
HttpClient client = HttpClient.newHttpClient();
for (String path : new String[] {"/static/", "/static/style.css",
"/static/missing.js"}) {
HttpResponse<String> r = client.send(
HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.ofString());
System.out.printf("%-20s %d %-26s %s%n", path, r.statusCode(),
r.headers().firstValue("content-type").orElse("-"),
r.body().strip().lines().findFirst().orElse(""));
}
server.stop(0);
}
}
Output:
/static/ 200 text/html <h1>Home</h1>
/static/style.css 200 text/css h1 { color: navy }
/static/missing.js 404 text/html; charset=UTF-8 <!DOCTYPE html>
The same server is available from the command line as jwebserver, which is handy for previewing a static site:
$ cd site
$ jwebserver -p 9000
Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::".
Serving C:\Users\me\site and subdirectories on 127.0.0.1 port 9000
URL http://127.0.0.1:9000/
127.0.0.1 - - [17/Oct/2026:21:48:42 +0200] "GET / HTTP/1.1" 200 -
Without -p it uses port 8000. It serves files only, with no caching headers, no compression and no HTTPS. It's meant for development and testing.
Canned responses and filters
Java 18 also added HttpHandlers with two helpers: of(status, headers, body) for a fixed response and handleOrElse(predicate, handler, fallback) to pick a handler per request. A Filter attached to a context runs code before or after its handler. Filter.afterHandler() and Filter.beforeHandler() create simple ones from a lambda:
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpHandlers;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Builtins {
public static void main(String[] args) throws Exception {
// A canned response: status, headers and body
HttpHandler health = HttpHandlers.of(200,
Headers.of("Content-Type", "application/json"), "{\"status\":\"ok\"}");
// GET or HEAD -> health, anything else -> 405
HttpHandler handler = HttpHandlers.handleOrElse(
req -> req.getRequestMethod().equals("GET") || req.getRequestMethod().equals("HEAD"),
health,
HttpHandlers.of(405, Headers.of("Allow", "GET, HEAD"), ""));
// A filter that runs after the handler: a one-line access log
Filter accessLog = Filter.afterHandler("access log", ex ->
System.out.printf("server: %s %s -> %d%n",
ex.getRequestMethod(), ex.getRequestURI(), ex.getResponseCode()));
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/health", handler).getFilters().add(accessLog);
server.start();
URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/health");
HttpClient client = HttpClient.newHttpClient();
for (String method : new String[] {"GET", "HEAD", "DELETE"}) {
HttpResponse<String> r = client.send(
HttpRequest.newBuilder(uri).method(method, HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.ofString());
System.out.printf("client: %-6s %d %s%n", method, r.statusCode(),
r.headers().firstValue("allow").map(a -> "Allow: " + a).orElse(r.body()));
}
server.stop(0);
}
}
Output:
server: GET /health -> 200
client: GET 200 {"status":"ok"}
server: HEAD /health -> 200
client: HEAD 200
server: DELETE /health -> 405
client: DELETE 405 Allow: GET, HEAD
HttpHandlers.of handles HEAD correctly by sending the headers without the body. Filters can also wrap the handler completely (to time it, check authentication or catch exceptions) by implementing doFilter(exchange, chain) and calling chain.doFilter(exchange). Building chains of such filters is covered in HTTP middleware.
A complete example: a small JSON API
This puts the pieces together: a to-do list API with a regex-based router, path parameters, query parameters, form bodies, JSON responses, proper 404/405/400 errors, a 500 safety net, virtual threads and a graceful shutdown.
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class TodoApi {
record Todo(int id, String title, boolean done) {
String toJson() {
return "{\"id\":%d,\"title\":%s,\"done\":%b}".formatted(id, quote(title), done);
}
}
interface Handler {
void handle(HttpExchange ex, Matcher path) throws IOException;
}
record Route(String method, Pattern pattern, Handler handler) {}
static final List<Route> routes = new ArrayList<>();
static final Map<Integer, Todo> todos = new ConcurrentSkipListMap<>();
static final AtomicInteger nextId = new AtomicInteger(1);
static void route(String method, String regex, Handler handler) {
routes.add(new Route(method, Pattern.compile(regex), handler));
}
public static void main(String[] args) throws IOException {
route("GET", "/todos", (ex, m) -> {
String done = parseQuery(ex.getRequestURI().getRawQuery()).get("done");
String json = todos.values().stream()
.filter(t -> done == null || t.done() == Boolean.parseBoolean(done))
.map(Todo::toJson)
.collect(Collectors.joining(",", "[", "]"));
send(ex, 200, json);
});
route("POST", "/todos", (ex, m) -> {
String form = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
String title = parseQuery(form).get("title");
if (title == null || title.isBlank()) {
send(ex, 400, "{\"error\":\"title is required\"}");
return;
}
Todo todo = new Todo(nextId.getAndIncrement(), title, false);
todos.put(todo.id(), todo);
ex.getResponseHeaders().set("Location", "/todos/" + todo.id());
send(ex, 201, todo.toJson());
});
route("GET", "/todos/(\\d+)", (ex, m) -> {
Todo todo = todos.get(Integer.parseInt(m.group(1)));
if (todo == null) send(ex, 404, "{\"error\":\"no such todo\"}");
else send(ex, 200, todo.toJson());
});
route("PUT", "/todos/(\\d+)/done", (ex, m) -> {
Todo todo = todos.computeIfPresent(Integer.parseInt(m.group(1)),
(id, t) -> new Todo(id, t.title(), true));
if (todo == null) send(ex, 404, "{\"error\":\"no such todo\"}");
else send(ex, 200, todo.toJson());
});
route("DELETE", "/todos/(\\d+)", (ex, m) -> {
todos.remove(Integer.parseInt(m.group(1)));
ex.sendResponseHeaders(204, -1);
});
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", TodoApi::dispatch);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("stopping...");
server.stop(2); // stop accepting, wait up to 2 seconds for open exchanges
}));
System.out.println("Listening on http://localhost:8080/");
}
static void dispatch(HttpExchange ex) throws IOException {
try {
String path = ex.getRequestURI().getPath();
Set<String> allowed = new TreeSet<>();
for (Route r : routes) {
Matcher m = r.pattern().matcher(path);
if (!m.matches()) continue;
if (r.method().equals(ex.getRequestMethod())) {
r.handler().handle(ex, m);
return;
}
allowed.add(r.method());
}
if (allowed.isEmpty()) {
send(ex, 404, "{\"error\":\"not found\"}");
} else {
ex.getResponseHeaders().set("Allow", String.join(", ", allowed));
send(ex, 405, "{\"error\":\"method not allowed\"}");
}
} catch (Exception e) {
e.printStackTrace();
if (ex.getResponseCode() == -1) send(ex, 500, "{\"error\":\"internal error\"}");
} finally {
ex.close();
}
}
static void send(HttpExchange ex, int status, String json) throws IOException {
byte[] body = json.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "application/json");
ex.sendResponseHeaders(status, body.length);
ex.getResponseBody().write(body);
}
// Parses "a=1&b=x+y" (query strings and HTML form bodies). Last value wins.
static Map<String, String> parseQuery(String raw) {
Map<String, String> params = new LinkedHashMap<>();
if (raw == null || raw.isEmpty()) return params;
for (String pair : raw.split("&")) {
int eq = pair.indexOf('=');
String key = eq < 0 ? pair : pair.substring(0, eq);
String value = eq < 0 ? "" : pair.substring(eq + 1);
params.put(URLDecoder.decode(key, StandardCharsets.UTF_8),
URLDecoder.decode(value, StandardCharsets.UTF_8));
}
return params;
}
// Minimal JSON string escaping. Use Jackson or Gson for anything bigger.
static String quote(String s) {
StringBuilder sb = new StringBuilder("\"");
for (char c : s.toCharArray()) {
switch (c) {
case '"' -> sb.append("\\\"");
case '\\' -> sb.append("\\\\");
case '\n' -> sb.append("\\n");
default -> {
if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
}
}
return sb.append('"').toString();
}
}
A session with curl:
$ curl -i -d 'title=Buy milk' http://localhost:8080/todos
HTTP/1.1 201 Created
Date: Sat, 17 Oct 2026 19:49:58 GMT
Content-type: application/json
Content-length: 40
Location: /todos/1
{"id":1,"title":"Buy milk","done":false}
$ curl --data-urlencode 'title=Write "article" & publish' http://localhost:8080/todos
{"id":2,"title":"Write \"article\" & publish","done":false}
$ curl -X PUT http://localhost:8080/todos/1/done
{"id":1,"title":"Buy milk","done":true}
$ curl http://localhost:8080/todos
[{"id":1,"title":"Buy milk","done":true},{"id":2,"title":"Write \"article\" & publish","done":false}]
$ curl 'http://localhost:8080/todos?done=false'
[{"id":2,"title":"Write \"article\" & publish","done":false}]
$ curl -i -X PATCH http://localhost:8080/todos/1
HTTP/1.1 405 Method Not Allowed
Date: Sat, 17 Oct 2026 19:49:58 GMT
Allow: DELETE, GET
Content-type: application/json
Content-length: 30
{"error":"method not allowed"}
$ curl -i -X POST http://localhost:8080/todos
HTTP/1.1 400 Bad Request
Date: Sat, 17 Oct 2026 19:49:59 GMT
Content-type: application/json
Content-length: 29
{"error":"title is required"}
$ curl -i -X DELETE http://localhost:8080/todos/1
HTTP/1.1 204 No Content
Date: Sat, 17 Oct 2026 19:49:59 GMT
$ curl http://localhost:8080/todos/1
{"error":"no such todo"}
$ curl http://localhost:8080/nope
{"error":"not found"}
Notes on the design:
- One context at
/sends every request todispatch(), which tries the routes in order. A route matches only if the regex matches the whole path (matches(), notfind()), so/todos/7/extrais a 404. When the path matches but the method doesn't, the response is 405 with anAllowheader, as HTTP requires. parseQuery()works for both query strings andapplication/x-www-form-urlencodedbodies, because they use the same encoding:&between pairs,=between name and value,+for spaces and%XXfor other bytes. That's why the secondcurluses--data-urlencode. With plain-dthe&would end the title early.- JSON is built by hand with a tiny
quote()helper to keep the example dependency-free. In real code use Jackson or Gson (see JSON in Java) for both reading and writing JSON. ConcurrentSkipListMapkeeps the to-dos sorted by id and is safe to use from many virtual threads at once.AtomicIntegerhands out unique ids.- The shutdown hook runs on Ctrl+C or
SIGTERM.server.stop(2)stops accepting new connections right away, then waits up to 2 seconds for exchanges in progress to finish before closing everything.
Configuration and limits
HttpServer is configured through a few system properties, set with -D on the command line:
| Property | Default | Meaning |
|---|---|---|
sun.net.httpserver.maxReqHeaders |
200 | Maximum number of request headers |
sun.net.httpserver.maxReqTime |
-1 (none) | Seconds allowed to read a request |
sun.net.httpserver.maxRspTime |
-1 (none) | Seconds allowed to write a response |
sun.net.httpserver.idleInterval |
30 | Seconds before an idle keep-alive connection is closed |
sun.net.httpserver.maxReqHeaderSize |
389120 | Maximum total size of request headers, in bytes |
jdk.httpserver.maxConnections |
-1 (none) | Maximum number of open connections |
There is no limit on the size of a request body. A handler that calls readAllBytes() on a huge upload will happily try to fit it all in memory. If the server is reachable by untrusted clients, check Content-Length and read the body through a size-limited loop.
For HTTPS there is HttpsServer, which works the same way but needs an SSLContext loaded from a key store via setHttpsConfigurator(). In production it's more common to run the plain HTTP server behind a reverse proxy (nginx, Caddy, a cloud load balancer) that terminates TLS.
When to use something else
| You need | Use |
|---|---|
| HTTP/2, WebSockets, high throughput | Jetty, Undertow, Netty (see WebSockets) |
| Routing, JSON binding, validation | Javalin, Helidon SE, Micronaut, Quarkus |
| A full application framework | Spring Boot (see REST APIs) |
| Servlets, WAR deployment | Tomcat, Jetty |
Summary
HttpServer.create(),createContext(),start()give you a working server with no dependencies.- In a handler: read the request, set headers, call
sendResponseHeaders()once, write the body, close the exchange. - The length argument is in bytes:
> 0forContent-Length,0for chunked,-1for no body. - Contexts match by string prefix. Write your own router for methods and path parameters.
- An uncaught exception drops the connection without a response. Wrap handlers so they send a 500 instead.
- The default executor is a single thread. Use
Executors.newVirtualThreadPerTaskExecutor(). SimpleFileServerandjwebserverserve static files.HttpHandlersandFiltercover canned responses and before/after hooks (see HTTP middleware).