Java SE 6 (代號 Mustang) 在網絡棧引入四大實用增強:NTLM 認證支持、內置輕量級 HTTP 服務器、完善的 Cookie 管理 API、國際化域名 (IDN) 支持。本文結合源碼級示例,演示如何在企業集成、測試桩、微服務網關等場景落地這些能力。
Basic 認證 Base64 編碼明文傳輸憑證,Digest 雖用 MD5 挑戰響應但仍易受中間人攻擊。企業內網普遍部署 **Windows 域控制器 + NTLM/Kerberos**,Java 6 前無法原生支持,只能手工構建 Socket 協議極其痛苦。
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String user = "DOMAIN\\username"; // 或 "username@domain"
return new PasswordAuthentication(user, "password".toCharArray());
}
});
// 可選:系統屬性避免重複拼接域名
// System.setProperty("http.auth.ntlm.domain", "DOMAIN");
HttpURLConnection 遇到 401 + WWW-Authenticate: NTLM 時,自動觸發上述回調完成握手,**業務代碼零感知**。
JDK 6 默認順序:GSS/SPNEGO (Kerberos) → Digest → NTLM → Basic。
Kerberos 通過 JAAS + GSS-API 實現,SPNEGO 協商機制自動選擇雙方均支持的最高強度協議。
HttpServer server = HttpServer.create(new InetSocketAddress(7778), 1); // backlog=1
server.createContext("/myapp/", exchange -> {
String response = "Hello, Java 6 HttpServer!";
exchange.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.getBytes());
}
});
server.setExecutor(null); // 默認執行器
server.start();
System.out.println("Server started on port 7778");
瀏覽器訪問 https://localhost:7778/myapp/ 即見響應。
createContext(path, handler) 支持前綴匹配,HttpExchange 封裝請求/響應、頭、體、Principal。server.createContext("/", new FilterChain(...)) 實現認證、日志、限流等橫切邏輯。HttpClient 或引入 Netty/Vert.x。CookieHandler (抽象)
└─ CookieManager (默認實現)
├─ CookieStore 存儲/檢索/過期清理
└─ CookiePolicy 接受/拒絕策略
├─ ACCEPT_ALL
├─ ACCEPT_NONE
└─ ACCEPT_ORIGINAL_SERVER (默認,同源策略)
HttpCookie: 不可變數據載體,支持 Netscape/RFC2109/RFC2965 三規範
// 1. 全局啟用,接受所有 Cookie(爬蟲/測試場景)
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// 2. 手動添加 Cookie(模擬登錄態)
HttpCookie sessionCookie = new HttpCookie("JSESSIONID", "abc123");
sessionCookie.setDomain("example.com");
sessionCookie.setPath("/");
sessionCookie.setSecure(true);
sessionCookie.setHttpOnly(true);
manager.getCookieStore().add(new URI("https://example.com/"), sessionCookie);
// 3. 發送請求時自動攜帶匹配 Cookie
URL url = new URL("https://example.com/api/user");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn 自動從 CookieManager 獲取並設置 Cookie 頭
// 4. 讀取響應中 Set-Cookie 並自動存儲
// 由 HttpURLConnection 內部完成,無需手動干預
// 5. 遍歷/清理 Cookie
List<HttpCookie> all = manager.getCookieStore().getCookies();
for (HttpCookie c : all) {
if (c.hasExpired()) manager.getCookieStore().remove(uri, c);
}
InMemoryCookieStore 進程重啟丟失。實現 CookieStore 接口對接 Redis/DB。CookiePolicy,謹慎評估安全風險(CSRF)。HttpCookie 支持屬性設置,確保合規。java.net.IDN 提供 toASCII()/toUnicode() 實現 Punycode 編解碼:
String unicode = "https://例子.测试";
String ascii = IDN.toASCII(unicode); // "https://xn--fsq.xn--0zwm56d"
URI uri = new URI(ascii); // 後續網絡調用使用 ASCII 形式
解決中文/阿拉伯文等非 ASCII 域名在 DNS、HTTP、證書中的互操作問題。
| 特性 | Java 6 方案 | 現代替代 (JDK 11+) | 遷移建議 |
|---|---|---|---|
| NTLM/Kerberos | Authenticator SPI | JDK 11 HttpClient 原生支持、Kerberos 憑證緩存 | 升級 HttpClient,簡化認證代碼 |
| 內嵌 HTTP Server | com.sun.net.httpserver | JDK 18+ jwebserver、Spring Boot 嵌入 Tomcat/Jetty/Undertow | 生產環境遷移成熟容器 |
| Cookie 管理 | CookieManager | HttpClient CookieHandler、Spring RestTemplate/ WebClient Cookie 支持 | 統一使用 HttpClient 生態 |
| IDN | java.net.IDN | ICU4J、Guava InternetDomainName | 繼續使用標準庫 |
Java SE 6 的網絡增強雖屬「小步快跑」,卻精準解決了企業集成中的**認證、測試、會話管理**三大痛點。理解其設計哲學(SPI 可插拔、標準 API、安全默認),有助於在現代技術棧中做出正確選型。