JDK 6+ 自帶 com.sun.net.httpserver.HttpServer(非標準 API 但廣泛可用),無需第三方依賴即可啟動 HTTP 服務。
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.InetSocketAddress;
class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
public class MyServer {
public static void main(String[] args) {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/myapp", new MyHandler());
server.setExecutor(null); // 使用默認執行器
server.start();
System.out.println("Server started on https://localhost:8000/myapp");
} catch (IOException e) { e.printStackTrace(); }
}
}
瀏覽器訪問 https://localhost:8000/myapp → 顯示 "This is the response"。
t.getRequestHeaders()、t.getRequestURI()、t.getRequestBody() 做路由分發。Content-Type、支援 Range 斷點續傳。HttpsServer + KeyStore 配置。