首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java SE 6 網絡新特性深度解析:HTTP 增強、輕量級 Server、Cookie 管理與 NTLM 認證

     編輯:Java 相關知識

概覽

Java SE 6 在網絡編程層面大幅增強,特別是 HTTP 協議支援:NTLM 認證、內嵌輕量級 HTTP Server、標準化 Cookie 管理、NetworkInterface 功能擴充、國際化域名 (IDN) 支援。

NTLM 認證支援

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。

輕量級 HTTP Server

內建 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。

標準化 Cookie 管理

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 */ }

NetworkInterface 功能擴充

新增實用查詢方法:

國際化域名 (IDN) 支援

java.net.IDN 提供 Unicode 域名與 ACE (ASCII Compatible Encoding) 互轉:

String unicode = "例子.測試";
String ascii = IDN.toASCII(unicode); // "xn--fsq092h.xn--0zwm56d"
String back = IDN.toUnicode(ascii);  // 還原

符合 RFC 3490/3491/3492 標準,支援非 ASCII 字符域名解析。

結語

Java SE 6 將 HTTP 客戶端/伺服端開發所需的認證、Cookie、嵌入式 Server、介面查詢、IDN 等能力納入標準庫,大幅降低網絡應用開發門檻與外部依賴。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方法用途
isUp()介面是否啟用
isLoopback()是否回環介面
isPointToPoint()是否點對點連結
supportsMulticast()是否支援多播
getHardwareAddress()取得 MAC 位址
getMTU()取得最大傳輸單元
isVirtual()是否虛擬介面