BackendBench
Coffee

Unravel › Java concepts › APIs and web

I/O and data

The built-in HTTP server

com.sun.net.httpserver.HttpServer is a tiny web server inside the JDK.

Learn these first

At a glance

Mental model

A food stall with one cook: you tell the cook which dish belongs to which menu number (the context path), and for each order they hand over the plate and the receipt.

What happens, in order
  1. 1HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/hello", exchange -> {...}); server.start();
  2. 2In the handler: read exchange.getRequestMethod(), getRequestURI(), getRequestHeaders() and getRequestBody(); send sendResponseHeaders(200, bytes.length) and write the body to getResponseBody(), then close the exchange
  3. 3Use server.setExecutor(Executors.newFixedThreadPool(8)) so requests are handled on several threads; the default runs them one by one on one thread
  4. 4It is great for a stub server in integration tests and for small toolsFor production applications use Spring Boot, Javalin, Helidon or similar.
Remember
Watch out
Forgetting to close the exchangeUsing the default single-threaded executor for slow handlersWriting the body before the headersExposing it publicly without authentication
Example (highlighted lines explain it)
import com.sun.net.httpserver.*;import java.io.*;import java.net.InetSocketAddress;import java.nio.charset.StandardCharsets;public class Hello {  public static void main(String[] args) throws IOException {    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);    server.createContext("/hello", exchange -> {      byte[] body = "hello".getBytes(StandardCharsets.UTF_8);      exchange.sendResponseHeaders(200, body.length);      try (OutputStream out = exchange.getResponseBody()) { out.write(body); }    });    server.setExecutor(java.util.concurrent.Executors.newFixedThreadPool(4));    server.start();  }}
  1. line 7 uses HttpServer, the core of The built-in HTTP server
  2. line 8 uses createContext, the core of The built-in HTTP server
  3. line 10 uses sendResponseHeaders, the core of The built-in HTTP server
  4. line 11 uses getResponseBody, the core of The built-in HTTP server
Read the full explanation (about 1 min)

com.sun.net.httpserver.HttpServer is a tiny web server inside the JDK. You register handlers for paths and write the response yourself: handy for tests, mocks, health checks and demos without a framework.

A mental model

A food stall with one cook: you tell the cook which dish belongs to which menu number (the context path), and for each order they hand over the plate and the receipt.

How it works

HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/hello", exchange -> {...}); server.start();

In the handler: read exchange.getRequestMethod(), getRequestURI(), getRequestHeaders() and getRequestBody(); send sendResponseHeaders(200, bytes.length) and write the body to getResponseBody(), then close the exchange.

Use server.setExecutor(Executors.newFixedThreadPool(8)) so requests are handled on several threads; the default runs them one by one on one thread.

It is great for a stub server in integration tests and for small tools. For production applications use Spring Boot, Javalin, Helidon or similar.

Going deeper

You are responsible for everything: content type headers, error responses (an exception in the handler gives a dropped connection), URL decoding, request size limits, TLS (HttpsServer), authentication.

sendResponseHeaders must be called before writing the body, and the length must match what you write (-1 for no body, 0 for chunked).

Close the HttpExchange (or its streams) or the connection leaks.

Under the hood

It runs a ServerImpl with a selector thread that accepts connections and dispatches to the executor. It supports HTTP/1.1 with keep-alive, but not HTTP/2.

Common mistakes

  • Forgetting to close the exchange.
  • Using the default single-threaded executor for slow handlers.
  • Writing the body before the headers.
  • Exposing it publicly without authentication.

How Unravel recognises it

When you paste code, Unravel looks for these signs of the built-in http server. Spotting them yourself is a good habit when you read unfamiliar code:

Part of a learning path

Related concepts

Frequently asked questions

What is The built-in HTTP server?

com.sun.net.httpserver.HttpServer is a tiny web server inside the JDK. You register handlers for paths and write the response yourself: handy for tests, mocks, health checks and demos without a framework.

What are the most common mistakes with The built-in HTTP server?

Forgetting to close the exchange. Using the default single-threaded executor for slow handlers. Writing the body before the headers. Exposing it publicly without authentication.

How can I see The built-in HTTP server in real code?

Paste your own Java into Unravel and it will point out where the built-in http server appears, explain how it works at the detail level you choose, and draw the flow of the code around it.