Java Reference ยท I/O and Files
The com.sun.net.httpserver package
Reference for the JDK's built-in HttpServer: create contexts and handlers, read requests, send responses, use executors, and test it with HttpClient on loopback.
The JDK ships a small HTTP server in the jdk.httpserver module, package com.sun.net.httpserver. You create an HttpServer, attach an HttpHandler to each path prefix (a "context"), and start it. It is meant for tests, tools, prototypes and local dashboards, not for production traffic. The com.sun prefix looks internal, but this package is a supported, documented API.
Since Java 18 there is also a ready-made static file server (SimpleFileServer, and the jwebserver command) in the same package family.
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 8080), 0); server.createContext("/hello", exchange -> { /* respond */ }); server.start();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public abstract class HttpServer static HttpServer create(InetSocketAddress addr, int backlog) throws IOException HttpContext createContext(String path, HttpHandler handler) @FunctionalInterface public interface HttpHandler { void handle(HttpExchange exchange) throws IOException; }
| Member | Description |
|---|---|
HttpServer.start() / stop(int delaySeconds) |
Starts the server thread; stops it after waiting up to the delay for exchanges to finish. |
HttpServer.setExecutor(Executor) |
Where handlers run. null means the thread that accepts connections. |
HttpServer.getAddress() |
The bound address, useful after binding to port 0. |
HttpExchange.getRequestMethod(), getRequestURI(), getRequestHeaders(), getRequestBody() |
Read the request. |
HttpExchange.getResponseHeaders() |
Mutable headers; set them before sendResponseHeaders. |
HttpExchange.sendResponseHeaders(int status, long length) |
Sends status and headers. Length 0 means chunked, -1 means no body. |
HttpExchange.getResponseBody() |
Stream for the body; closing it ends the exchange. |
HttpContext.getFilters(), setAuthenticator(...) |
Filters and authentication for a path. |
SimpleFileServer.createFileServer(addr, path, outputLevel) |
A static file server (Java 18+). |
Throws: IOException from create and the handler methods, BindException if the port is taken, IllegalArgumentException for a bad length.
Usage notes
- Contexts match by prefix.
/helloalso matches/hello/world; the longest matching context wins, and an unmatched path gets a built-in 404. - Close the exchange. Either close the response body stream or call
exchange.close(). A handler that returns without closing leaves the client waiting. - Order matters. Set response headers first, then call
sendResponseHeaders, then write the body. After that, header changes are ignored. - Content length. Pass the exact byte length for fixed responses (
bytes.length, notstring.length()).0switches to chunked encoding;-1signals no body, as for 204 or HEAD. - Threads. The default executor runs handlers one after another on a single thread, so a slow handler blocks everyone. Pass a pool or
Executors.newVirtualThreadPerTaskExecutor()(Java 21+). - Exceptions in a handler close the connection without a clean error response; wrap handler logic in try/catch and send a 500 yourself.
- Request bodies must be read before the response ends. The server discards unread data.
- No routing, templating, sessions or HTTP/2. For anything beyond a small tool, use a framework such as Spring Boot, Javalin or Helidon.
- Production use is discouraged by the JDK documentation; there is no TLS-by-default and only basic limits. HTTPS is available through
HttpsServer. - Binding. Bind to
127.0.0.1for local tools so other machines cannot reach them.
Related
HttpClient, Sockets, URI and URL,ExecutorService- Lessons: Networking basics, Sockets