JDK 6 引入 com.sun.net.httpserver 套件,提供簡易的內嵌 HTTP/HTTPS 伺服器實作,支援 HTTP 1.1 部分規格。開發者只需實作 HttpHandler 介面,即可快速建立嵌入式 Web 服務。
HttpServer:伺服器主體,管理連線與執行緒池HttpExchange:封裝單次 HTTP 請求/回應交換HttpHandler:處理請求的回呼介面,單一方法 handle(HttpExchange)import com.sun.net.httpserver.*;
import java.io.*;
import java.net.InetSocketAddress;
public class SimpleHttpServer {
public static void main(String[] args) throws IOException {
// 1. 建立伺服器綁定埠 8888
HttpServer server = HttpServer.create(new InetSocketAddress(8888), 0);
// 2. 註冊上下文路徑與處理器
server.createContext("/chinajash", new MyHandler());
// 3. 使用預設執行緒池並啟動
server.setExecutor(null);
server.start();
System.out.println("Server started on port 8888");
}
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
// 讀取請求本文 (可選)
InputStream is = exchange.getRequestBody();
// 準備回應
String response = "<h3>Happy New Year 2007! -- Chinajash</h3>";
exchange.sendResponseHeaders(200, response.length());
// 輸出回應本文
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
HttpsServer 與 SSLContext 啟用 TLS未實作的 HTTP 1.1 特性(如 Chunked Encoding、Pipeline)可透過繼承 HttpServer 或自訂 HttpHandler 處理。生產環境高併發場景建議替換為 Netty、Undertow 或 Jetty 等成熟框架。
JDK 內建 HTTP Server 雖功能精簡,但零依賴、啟動極快,極適合測試、原型、工具類應用與輕量級嵌入場景,是 Java 開發者工具箱中的利器。