Back to results for “Applications”
Java › Java Networking & HTTP Client

How would you implement a simple HTTP server (not just a client) using the lightweight com.sun.net.httpserver.HttpServer class bundled with the JDK, without a full framework like Spring?

Advanced

Answer

com.sun.net.httpserver.HttpServer (available in the JDK itself, though technically part of an internal/unsupported-officially package historically, now more formally exposed) provides a minimal, dependency-free way to stand up a basic HTTP server for simple use cases (a local development mock server, a lightweight health-check endpoint, a simple internal admin tool) without pulling in a full web framework, by registering a HttpHandler for specific URL paths that receives the raw HttpExchange (giving access to the request and letting you write the response) -- while genuinely useful for its simplicity in narrow scenarios, it lacks the routing, middleware, and ecosystem support a full framework like Spring Boot or Javalin provides, making it unsuitable for anything beyond simple, low-traffic, internal-use cases.
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/health", exchange -> {
    String response = "OK";
    exchange.sendResponseHeaders(200, response.length());
    try (OutputStream os = exchange.getResponseBody()) {
        os.write(response.getBytes());
    }
});
server.setExecutor(Executors.newFixedThreadPool(4));
server.start();
Real-world example A local development tool needing a simple mock HTTP endpoint for testing purposes (simulating a third-party API's responses) spins up a lightweight com.sun.net.httpserver.HttpServer instance directly, avoiding the overhead and configuration complexity of bringing in a full web framework dependency purely for this narrow, temporary testing need.

Common follow-ups: What are the specific limitations of this built-in server that would make it unsuitable for a genuine production-facing API?;Why is this class historically considered part of an 'internal' JDK package, and how does that affect its long-term API stability guarantees?