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.
Code
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.HttpServermust 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
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Are there third-party dependencies?
- `com.sun.net.httpserver.HttpServer` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.