HttpServer Minimal Embedded Endpoint

Spin up a com.sun.net.httpserver.HttpServer on an ephemeral port, register one handler, and stop it cleanly — no external dependencies.

JavaCli Tooling

Code

snippet
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class MiniEndpoint {

    public static void main(String[] args) throws Exception {
        // 端口 0 = 由系统分配临时端口,避免测试里端口冲突
        HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);

        server.createContext("/ping", exchange -> {
            byte[] body = "pong".getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().set("Content-Type", "text/plain");
            exchange.sendResponseHeaders(200, body.length);
            try (var out = exchange.getResponseBody()) {
                out.write(body);
            }
        });

        server.start();
        System.out.println("listening on port " + server.getAddress().getPort());

        // HttpServer 没有关闭钩子:显式 stop(0) 立即终止,连接不会挂住
        server.stop(0);
        System.out.println("stopped");
    }
}

What the code does

All of the logic lives in the class MiniEndpoint.

Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

What to watch for

  • com.sun.net.httpserver.HttpServer must be installed first — the snippet imports it directly.

Applying it

Running the file prints labeled results such as listening on port, stopped — each operation’s effect is visible in the output.

Statements that matter

HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
exchange.getResponseHeaders().set("Content-Type", "text/plain");
byte[] body = "pong".getBytes(StandardCharsets.UTF_8);

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`com.sun.net.httpserver.HttpServer` — install it with the package manager before running.