Skip to lesson

Starting an HttpServer and adding handlers

A phone app cannot call the Java methods of your ShopLite shop. It needs a program that waits on a port and answers web requests in HTTP. The JDK already contains a small one.

The jdk.httpserver module: HttpServer, HttpHandler, HttpExchange

HttpServer is the JDK class (package com.sun.net.httpserver, module jdk.httpserver) that listens on a port and sends each request to the handler of the matching path. It needs no download and no Maven dependency.

Three types do the work: HttpServer, HttpHandler and HttpExchange. Example 1 writes the smallest handler and sends one request to it.

Example 1 · A handler class, a context and one request

HelloServerDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;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;
/** The handler: called once for every request that reaches its context. */class HelloHandler implements HttpHandler {    @Override    public void handle(HttpExchange exchange) throws IOException {        System.out.println("  handler got " + exchange.getRequestMethod() + " " + exchange.getRequestURI());        byte[] body = "Hello from ShopLite".getBytes(StandardCharsets.UTF_8);        exchange.sendResponseHeaders(200, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class HelloServerDemo {    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/hello", new HelloHandler());        server.start();        System.out.println("Server started");
        String url = "http://127.0.0.1:" + server.getAddress().getPort() + "/hello";        HttpClient client = HttpClient.newHttpClient();        HttpResponse<String> response = client.send(HttpRequest.newBuilder(URI.create(url)).build(),                HttpResponse.BodyHandlers.ofString());        System.out.println("Client got " + response.statusCode() + ": " + response.body());
        server.stop(0);        System.out.println("Server stopped");    }}
Output
Server started
  handler got GET /hello
Client got 200: Hello from ShopLite
Server stopped

What this code does

  • HelloHandler implements HttpHandler. Its handle method sends status 200 with the body length in bytes, writes the body and closes the stream, which ends the exchange.
  • create with port 0 takes any free port, createContext("/hello", ...) connects the path to the handler, and start() returns at once. The HttpClient from the Calling APIs module then plays the browser, and stop(0) shuts the server down.

An HttpHandler has one method, handle(HttpExchange exchange), that you write. An HttpExchange is one request together with its response: you read the request from it and write your answer into it.

Why learn this when Spring Boot exists? Every Java web framework repeats the same steps: listen, match the path, call your code, write the status, headers and body. Doing them once by hand shows what the framework hides, so its errors make sense later.

The package starts with com.sun, but it is a documented, supported JDK API (since Java 6). It is good for learning, tests and small tools. Busy public websites usually run a framework on a server such as Tomcat or Netty.

create, createContext and start

A context is a path such as /hello connected to a handler with createContext. The server sends every request whose path starts with that text to the handler.

create opens the port, createContext connects a path to a handler, and start begins answering. Example 2 keeps a server running on port 8080.

Example 2 · A server that keeps running on port 8080

Runs in: a terminal: run it with java HelloServer.java and leave it running; stop it with Ctrl+C

HelloServer.javaJava
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.nio.charset.StandardCharsets;import java.time.LocalTime;
public class HelloServer {
    public static void main(String[] args) throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);        server.createContext("/hello", HelloServer::hello);        server.createContext("/api/v1/status", HelloServer::status);        server.start();        System.out.println("ShopLite hello server on http://localhost:8080 (Ctrl+C to stop)");        System.out.println("main() has ended, but the server thread keeps the program running");    }
    static void hello(HttpExchange exchange) throws IOException {        send(exchange, 200, "text/plain; charset=utf-8", "Hello from ShopLite\n");    }
    static void status(HttpExchange exchange) throws IOException {        System.out.println(LocalTime.now().withNano(0) + " " + exchange.getRequestMethod() + " "                + exchange.getRequestURI());        send(exchange, 200, "application/json", "{\"status\":\"UP\"}");    }
    static void send(HttpExchange exchange, int status, String type, String text) throws IOException {        byte[] body = text.getBytes(StandardCharsets.UTF_8);        exchange.getResponseHeaders().set("Content-Type", type);        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
Sample output
ShopLite hello server on http://localhost:8080 (Ctrl+C to stop)
main() has ended, but the server thread keeps the program running
11:06:40 GET /api/v1/status

What this code does

  • Two contexts, each with a method reference as its handler. main prints two lines and ends, but the server thread keeps the JVM alive, so the program waits for requests.
  • The last line is printed by status when a request arrives (here from curl in Example 5). send sets Content-Type before sendResponseHeaders, because the headers leave together with the status line.

The address is an InetSocketAddress: new InetSocketAddress(8080) listens on every network connection of your computer, new InetSocketAddress("127.0.0.1", 8080) only on this computer. The backlog is how many connections may wait while the server is busy; 0 means the system default. Port 0 asks the system for any free port, which is handy in tests.

start() returns at once, yet the program keeps running: the server thread is not a daemon thread, so the JVM stays alive until you press Ctrl+C or call server.stop(seconds). A handler can be a class, a lambda or a method reference such as HelloServer::hello.

Order of execution

From startup to the first answer

Put the steps in the order they happen.

sendResponseHeaders, the length rules and closing the exchange

sendResponseHeaders sends the status line and all headers in one go, so set the headers first. Its length argument counts bytes: above 0 means exactly that many bytes follow, 0 means chunked, -1 means no body.

Set the headers, call sendResponseHeaders, write the body, then close the exchange. Example 3 shows the three length cases; Example 4 shows two mistakes.

Example 3 · Fixed length, chunked and no body

ResponseLengthDemo.javaJava
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;
public class ResponseLengthDemo {    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/fixed", exchange -> {            byte[] body = "Fee receipt 1042: paid".getBytes(StandardCharsets.UTF_8);            exchange.sendResponseHeaders(200, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.createContext("/chunked", exchange -> {            exchange.sendResponseHeaders(200, 0);            try (OutputStream out = exchange.getResponseBody()) {                for (int roll = 1; roll <= 3; roll++) {                    out.write(("roll " + roll + " present\n").getBytes(StandardCharsets.UTF_8));                }            }        });        server.createContext("/empty", exchange -> {            exchange.sendResponseHeaders(204, -1);            exchange.close();        });        server.start();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();        HttpClient client = HttpClient.newHttpClient();        try {            for (String path : new String[] {"/fixed", "/chunked", "/empty"}) {                HttpResponse<String> r = client.send(HttpRequest.newBuilder(URI.create(base + path)).build(),                        HttpResponse.BodyHandlers.ofString());                System.out.println(path + " -> " + r.statusCode()                        + ", content-length " + r.headers().firstValue("content-length").orElse("(none)")                        + ", transfer-encoding " + r.headers().firstValue("transfer-encoding").orElse("(none)"));                if (r.body().isEmpty()) {                    System.out.println("   (no body)");                }                r.body().lines().forEach(line -> System.out.println("   " + line));            }        } finally {            server.stop(0);        }    }}
Output
/fixed -> 200, content-length 22, transfer-encoding (none)
   Fee receipt 1042: paid
/chunked -> 200, content-length (none), transfer-encoding chunked
   roll 1 present
   roll 2 present
   roll 3 present
/empty -> 204, content-length (none), transfer-encoding (none)
   (no body)

What this code does

  • /fixed passes the byte count, so the client sees content-length 22. /chunked passes 0 and writes three lines; the client sees transfer-encoding chunked and no length.
  • /empty passes -1 with status 204: no length, no chunks and no body. exchange.close() ends the exchange because there is no body stream to close.

Example 4 · Mistakes: characters instead of bytes, and no close

HandlerMistakesDemo.javaJava
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.concurrent.ExecutionException;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class HandlerMistakesDemo {    public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        String fee = "Hostel fee: ₹45000";        System.out.println("characters: " + fee.length() + ", UTF-8 bytes: "                + fee.getBytes(StandardCharsets.UTF_8).length);
        server.createContext("/wrong-length", exchange -> {            exchange.sendResponseHeaders(200, fee.length());            try (OutputStream out = exchange.getResponseBody()) {                out.write(fee.getBytes(StandardCharsets.UTF_8));            } catch (IOException e) {                System.out.println("  server: " + e.getMessage());            }        });        server.createContext("/right-length", exchange -> {            byte[] body = fee.getBytes(StandardCharsets.UTF_8);            exchange.sendResponseHeaders(200, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.createContext("/never-closed", exchange -> {            exchange.sendResponseHeaders(200, 0);            exchange.getResponseBody().write(fee.getBytes(StandardCharsets.UTF_8));        });        server.start();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();        HttpClient client = HttpClient.newHttpClient();        try {            for (String path : new String[] {"/wrong-length", "/right-length", "/never-closed"}) {                HttpRequest request = HttpRequest.newBuilder(URI.create(base + path)).build();                try {                    HttpResponse<byte[]> r = client.sendAsync(request, HttpResponse.BodyHandlers.ofByteArray())                            .get(1, TimeUnit.SECONDS);                    System.out.println(path + " -> " + r.statusCode() + ", got " + r.body().length + " bytes");                } catch (TimeoutException e) {                    System.out.println(path + " -> no complete response after 1 s");                }            }        } finally {            server.stop(0);        }    }}
Output
characters: 18, UTF-8 bytes: 20
  server: too many bytes to write to stream
/wrong-length -> no complete response after 1 s
/right-length -> 200, got 20 bytes
/never-closed -> no complete response after 1 s

What this code does

  • /wrong-length promises 18 bytes (the character count) and then writes 20. The server throws IOException: too many bytes to write to stream and sends no body, so the client waits for bytes that never come.
  • /never-closed starts a chunked body but never closes the stream, so the end marker is never sent and the client waits again. /right-length sends body.length and closes: the full 20 bytes arrive at once.
  • sendAsync(...).get(1, TimeUnit.SECONDS) puts a time limit on the whole response, body included, so the demo does not hang. A real client would show an error to the user instead.

The length argument is a promise, and it counts bytes, not characters:

  • length > 0: exactly that many bytes follow; the client gets a Content-length header.
  • 0: the length is not known yet; the body goes out in pieces (Transfer-encoding: chunked).
  • -1: no body at all, which is what 204 No Content needs.
  • In UTF-8 the rupee sign ₹ is 3 bytes, so "₹45000".length() is 6 but the body is 8 bytes. Always send text.getBytes(UTF_8).length.

Set headers with exchange.getResponseHeaders().set(name, value) before the call, because they go out together with the status.

Predict the output

Which length goes in?

Pick the answer for each case.

Round 1 of 3

How many bytes does the body hold?

byte[] body = "₹45000".getBytes(StandardCharsets.UTF_8);
System.out.println(body.length);
Closing the exchange ends the response: it frees the connection and, in chunked mode, sends the final empty chunk that tells the client "the body is complete". Use try (OutputStream out = exchange.getResponseBody()) or try (exchange) so it closes even after an exception.

Testing it with curl and the browser

curl is a command-line program that sends one HTTP request and prints the response. curl -i URL shows the status line and headers above the body; curl -i -X DELETE URL sends another method.

Example 5 starts the server from Example 2 and calls it with curl -i. Read the status line and the headers before the body.

Example 5 · curl against the running server

Terminal
curl -i http://localhost:8080/hellocurl -i http://localhost:8080/api/v1/statuscurl -i -X DELETE http://localhost:8080/hellocurl -i http://localhost:8080/
Sample output
$ curl -i http://localhost:8080/hello
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2026 05:36:39 GMT
Content-type: text/plain; charset=utf-8
Content-length: 20

Hello from ShopLite
$ curl -i http://localhost:8080/api/v1/status
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2026 05:36:40 GMT
Content-type: application/json
Content-length: 15

{"status":"UP"}
$ curl -i -X DELETE http://localhost:8080/hello
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2026 05:36:40 GMT
Content-type: text/plain; charset=utf-8
Content-length: 20

Hello from ShopLite
$ curl -i http://localhost:8080/
HTTP/1.1 404 Not Found
Content-Length: 50
Content-Type: text/html
Connection: close

<h1>404 Not Found</h1>No context found for request

What this code does

  • With Example 2 running, curl -i shows exactly what the handlers sent: the status line, Content-type and Content-length (the JDK capitalises only the first letter), a blank line, then the body.
  • DELETE /hello still gets 200, because the handler ignores the method. / matches no context, so the JDK answers with its own HTML 404 page and closes the connection.

The browser is fine for quick GET checks: open http://localhost:8080/hello. The JDK writes the headers your handler sends with only the first letter in capitals (Content-type, Content-length), which is allowed because header names are case-insensitive. A path that matches no context gets the JDK's own HTML page 404 Not Found. A DELETE to /hello still gets 200, because this handler never looks at the method; routing by method comes in the next lesson.

The browser also sends requests you did not ask for, most often GET /favicon.ico for the tab icon, so expect to see it if your server prints every request.

"Address already in use" and other startup errors

BindException is the error Address already in use: another program already listens on that port, very often your own server still running in another terminal. Only one program can own a port at a time.

Starting a second server on the same port fails at once. Example 6 catches the error and prints a message a person can act on.

Example 6 · Port in use and other startup errors

StartupErrorsDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.BindException;import java.net.InetSocketAddress;
public class StartupErrorsDemo {
    /** Starts a server, turning "port in use" into a message a person can act on. */    static HttpServer startOn(int port) throws IOException {        try {            HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);            server.start();            return server;        } catch (BindException e) {            throw new IllegalStateException("The port is already in use."                    + " Stop the other program or choose another port.", e);        }    }
    public static void main(String[] args) throws IOException {        HttpServer first = startOn(0);        int port = first.getAddress().getPort();        System.out.println("First server is running");
        try {            startOn(port);        } catch (IllegalStateException e) {            System.out.println("Second server: " + e.getMessage());            System.out.println("  cause: " + e.getCause().getClass().getName());        }
        try {            first.createContext("/hello", exchange -> exchange.close());            first.createContext("/hello", exchange -> exchange.close());        } catch (IllegalArgumentException e) {            System.out.println("Same context twice: " + e.getMessage());        }
        try {            first.createContext("hello", exchange -> exchange.close());        } catch (IllegalArgumentException e) {            System.out.println("Path without /: " + e.getMessage());        }
        try {            first.start();        } catch (IllegalStateException e) {            System.out.println("start() twice: " + e.getMessage());        }        first.stop(0);    }}
Output
First server is running
Second server: The port is already in use. Stop the other program or choose another port.
  cause: java.net.BindException
Same context twice: cannot add context to list
Path without /: Illegal value for path or protocol
start() twice: server in wrong state

What this code does

  • startOn catches BindException and throws a clear message instead, keeping the original exception as the cause for the log. The second server fails because the first one owns that port.
  • The other three mistakes throw at once: the same context twice, a path without /, and start() on a running server. Each is a programming error, so the fix is in the code, not in a retry.

Stop the other program (Ctrl+C in its terminal) or choose another port. To see who holds port 8080, run netstat -ano | findstr :8080 on Windows (the last column is the process id) or lsof -i :8080 on macOS; on Windows the message ends with : bind.

Other mistakes fail at once with an exception: the same path in createContext twice (cannot add context to list), a path without the leading / (Illegal value for path or protocol), and start() on a server that already started or was stopped (server in wrong state). A stopped HttpServer cannot start again; create a new one.

Fix the error

Fix the startup error

Read the error, then pick the line that replaces the marked one.

Round 1 of 2

Two contexts use the same path. Fix line 4.

HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/products", ProductsServer::list);
server.createContext("/orders", OrdersServer::list);
server.createContext("/products", ProductsServer::count);
server.start();

Error

Exception in thread "main" java.lang.IllegalArgumentException: cannot add context to list

Next step

Check your understanding

12 quick questions