Java java.net.URL 類是網絡編程的入口,封裝了統一資源定位符的解析、連接建立、數據流讀寫。本文系統講解 URL 結構、創建方式、相對/絕對路徑、組件拆解、異常處理及實際資源加載示例。
protocol://host:port/path?query#fragment
│ │ │ │ │ │
│ │ │ │ │ └─ 片段標識(錨點)
│ │ │ │ └─ 查詢參數
│ │ │ └─ 資源路徑(文件路徑)
│ │ └─ 端口號(可選,默認 80/443)
│ └─ 主機名/IP
└─ 協議(http, https, ftp, file, jar...)
// 2.1 絕對 URL 字符串
URL url1 = new URL("https://www.example.com:8080/path/file.html?k=v#anchor");
// 2.2 基礎 URL + 相對路徑(常用於 HTML 頁面內鏈接解析)
URL base = new URL("https://www.example.com/base/");
URL url2 = new URL(base, "sub/page.html"); // https://www.example.com/base/sub/page.html
URL url3 = new URL(base, "../other.html"); // https://www.example.com/other.html
URL url4 = new URL(base, "#section2"); // https://www.example.com/base/#section2
// 2.3 協議、主機、路徑、端口分別指定
URL url5 = new URL("http", "www.example.com", "/path/file.html");
URL url6 = new URL("http", "www.example.com", 8080, "/path/file.html");
// 2.4 URI 轉換(推薦現代 API)
URI uri = new URI("https://www.example.com/path");
URL url7 = uri.toURL();
URL url = new URL("https://user:pass@www.example.com:8080/path/file.html?query=1#frag");
url.getProtocol() // "http"
url.getHost() // "www.example.com"
url.getPort() // 8080(未指定返回 -1)
url.getFile() // "/path/file.html?query=1"(路徑+查詢)
url.getPath() // "/path/file.html"
url.getQuery() // "query=1"
url.getRef() // "frag"(fragment)
url.getAuthority() // "user:pass@www.example.com:8080"
url.getUserInfo() // "user:pass"
url.toString() // 完整 URL 字符串
url.toExternalForm()// 同 toString()
try {
URL url = new URL("htp://invalid"); // 協議拼寫錯誤
} catch (MalformedURLException e) {
System.err.println("無效 URL 格式: " + e.getMessage());
// 記錄日誌、拋出業務異常、使用默認值等
}
public String fetchContent(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
conn.setRequestProperty("User-Agent", "Java/1.8");
int code = conn.getResponseCode();
if (code != 200) throw new IOException("HTTP " + code);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) sb.append(line).append('\n');
return sb.toString();
} finally {
conn.disconnect();
}
}
// Swing
ImageIcon icon = new ImageIcon(new URL("https://example.com/logo.png"));
JLabel label = new JLabel(icon);
// JavaFX
Image img = new Image("https://example.com/logo.png");
ImageView view = new ImageView(img);
../ 向上一級目錄,./ 當前目錄。/ 開頭為絕對路徑(相對於域根)。#anchor 僅在客戶端使用,不發送給服務器。URI 類進行構建與解析(更嚴格符合 RFC 3986),最後 uri.toURL() 獲取 URL。InputStream 分塊寫入磁盤,避免 OOM。HttpURLConnection。掌握 URL 類的創建、解析與流式讀取,是 Java 網絡編程的基石。