Java SE 6 在網絡編程層面大幅增強,特別是 HTTP 協議支援:NTLM 認證、內嵌輕量級 HTTP Server、標準化 Cookie 管理、NetworkInterface 功能擴充、國際化域名 (IDN) 支援。
Windows 域環境常用的挑戰/回應認證機制。Java 6 前需自行實現協議極其複雜,現只需繼承 Authenticator:
class NtlmAuthenticator extends Authenticator {
private static final String DOMAIN = "DOMAIN";
private static final String USER = "user";
private static final String PWD = "password";
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(DOMAIN + "\\" + USER, PWD.toCharArray());
}
}
// 全域啟用
Authenticator.setDefault(new NtlmAuthenticator());
亦可設定系統屬性 http.auth.ntlm.domain 簡化代碼。認證協商順序:GSS/SPNEGO → Digest → NTLM → Basic。
內建 com.sun.net.httpserver.HttpServer,無需外部容器即可快速構建測試/嵌入式服務:
HttpServer server = HttpServer.create(new InetSocketAddress(7778), 1);
server.createContext("/myapp", new HttpHandler() {
public void handle(HttpExchange ex) throws IOException {
String resp = "Hello World!";
ex.sendResponseHeaders(200, resp.length());
try (OutputStream os = ex.getResponseBody()) { os.write(resp.getBytes()); }
}
});
server.setExecutor(null); // 使用預設執行緒池
server.start();
瀏覽器訪問 https://localhost:7778/myapp 即見回應。支援多 Context 映射不同 Handler。
Java 6 完整實作 CookieHandler 抽象體系:
HttpCookie:代表單一 Cookie,支援 Netscape、RFC 2109、RFC 2965 三種規範。CookiePolicy:決定接受/拒絕策略 (ACCEPT_ALL, ACCEPT_NONE, ACCEPT_ORIGINAL_SERVER)。CookieStore:持久化儲存,自動清理過期 Cookie。CookieManager:核心協調者,整合 Policy 與 Store。CookieManager mgr = new CookieManager();
mgr.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(mgr);
// 儲存
HttpCookie ck = new HttpCookie("sid", "abc123");
mgr.getCookieStore().add(uri, ck);
// 讀取
for (HttpCookie c : mgr.getCookieStore().get(uri)) { /* use c */ }
新增實用查詢方法:
| 方法 | 用途 |
|---|---|
isUp() | 介面是否啟用 |
isLoopback() | 是否回環介面 |
isPointToPoint() | 是否點對點連結 |
supportsMulticast() | 是否支援多播 |
getHardwareAddress() | 取得 MAC 位址 |
getMTU() | 取得最大傳輸單元 |
isVirtual() | 是否虛擬介面 |