Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 11 / Topic 3 of 10

A local server for every HTTP example in this part

java.net.http.HttpClient (next section) needs something to talk to, and this course never calls the public internet — a lesson that depends on a real website is a lesson that breaks the day that website changes, is slow, or is simply unreachable. The fix is com.sun.net.httpserver.HttpServer, a plain, JDK-only HTTP server with no third-party dependency at all. Every HTTP example in this part starts one, talks to it over http://localhost:<port>, and stops it before the program exits. Think of a driving test on a closed track instead of live traffic: the car (your HttpClient code) behaves exactly the same way it would on a real road, but nothing about the lesson depends on what some other car two kilometers away happens to be doing right now.

HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);  // port 0 = "give me any free port"
server.createContext("/ping", exchange -> {
    byte[] body = "pong".getBytes(StandardCharsets.UTF_8);
    exchange.getResponseHeaders().add("Content-Type", "text/plain");
    exchange.sendResponseHeaders(200, body.length);
    exchange.getResponseBody().write(body);
    exchange.close();                       // every exchange MUST be closed, or the client hangs
});
server.start();
int port = server.getAddress().getPort();   // the port that was actually picked
$ javac LocalTestServer.java
$ java LocalTestServer
Local server listening on http://localhost:49417
GET /ping -> 200 pong
GET /missing-for-real -> 404 not found
Server stopped

The port number is (varies) — a fresh free port every run, which is exactly why the code reads it back from server.getAddress() instead of hard-coding one. server.stop(0) matters too: HttpServer runs on its own background thread, and an un-stopped server would keep the JVM alive after main returns.

🔍 Going deeper: a real HTTPS call differs only in the URI's scheme (https://) and the TLS handshake underneath, which HttpClient does for you automatically — nothing about the request-building or response-reading code you see in this part changes.

Full program: examples/LocalTestServer.java.

Done here? The practice set for Part 11 — including the solutions — is on the part page.

Search the guide