java.net.URL 代表指向網絡資源的指針。資源不僅是文件,還包括數據庫查詢、搜索引擎、動態生成內容等。
scheme://host:port/path?query#fragment │ │ │ │ │ │ │ │ │ └─ 片段標譐 (客戶端處理) │ │ │ └─ 查詢字符串 (參數) │ │ └─ 資源路徑 │ └─ 端口 (默認由 scheme 決定) └─ 協議 (http, https, ftp, file, jar, jndi...)
HTML 頁面常用相對路徑 (../images/logo.png)。解析時繼承基礎 URL 的 scheme/host/port。new URL(base, relative) 自動合成。
URL 不處理轉義,不識別等價編碼形式URI (RFC 2396) 嚴格規範編碼/解碼,推薦用 URI 構建/規範化,再 toURL() 獲取連接URLEncoder/URLDecoder (application/x-www-form-urlencoded),非 RFC 2396
// 完整字符串
new URL("https://example.com:8080/path?k=v#frag");
// 協議、主機、端口、文件
new URL("http", "example.com", 8080, "/path");
// 協議、主機、文件 (默認端口)
new URL("http", "example.com", "/path");
// 基礎 URL + 相對路徑
URL base = new URL("https://example.com/app/");
URL resource = new URL(base, "images/logo.png"); // 自動合成
| 方法 | 返回類型 | 適用場景 | 特點 |
|---|---|---|---|
url.getContent() | Object | 簡單獲取、Content-Type 已知 | 依賴 ContentHandler 機制、類型不確定、易拋異常 |
url.openStream() | InputStream | 快速讀取二進制/文本流 | 最輕量、無連接配置、默認 GET |
url.openConnection() | URLConnection | 需控制請求頭、超時、重定向、POST | 功能最全、可轉型 HttpURLConnection |
new Scanner(url.openStream()) | Scanner | 文本逐行/按模式解析 | 便利 API、自動關閉資源 |
public String fetch(String urlStr, int timeoutMs) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(timeoutMs);
conn.setReadTimeout(timeoutMs);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 Java Client");
try (InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, StandardCharsets.UTF_8))) {
return reader.lines().collect(Collectors.joining("\n"));
} catch (IOException e) {
// 嘗試讀取錯誤流
try (InputStream err = conn.getErrorStream()) {
if (err != null) { /* 記錄錯誤詳情 */ }
}
throw e;
}
}
測試代碼遍歷 schemes 數組嘗試構建 URL。典型支持:
擴展機制:協議處理器 (URLStreamHandler) 可動態註冊自定義 scheme (如 s3://, hdfs://),配置 java.protocol.handler.pkgs 系統屬性。
toURL(),避免編碼陷阱HttpClient (HTTP/2、異步、Reactive)、OkHttp、Apache HttpClient 5 — 比 HttpURLConnection 更強StandardCharsets.UTF_8,勿依賴平台默認URL 是 Java 網絡編程的入口。理解其結構、掌握四種獲取資源 API 的差異、善用 URLConnection 精細控制、遷移至現代 HttpClient,是構建健壯網絡應用的基石。