<applet> 標籤,定位並下載遠端位元碼執行這兩者核心都依賴 java.net.URL 類別實現高層級網路互動。
URL(Uniform Resource Locator,統一資源定位器)包含兩個主要部分:
protocolID:resourceName │ │ │ └─ 資源名稱(主機名、路徑、連接埠、錨點等) └─ 協議識別符(http, ftp, file, news 等)
範例:https://java.sun.com/index.html
httpjava.sun.com/index.html#section1(可選)URL url = new URL("https://www.example.com/path/file.html");
相對 URL 依賴一個基底 URL,常用於 HTML 連結:
URL base = new URL("https://www.example.com/");
URL relative = new URL(base, "subpage.html"); // 同目錄下檔案
URL anchor = new URL(base, "page.html#section2"); // 錨點連結
建構子:URL(URL baseURL, String relativeURL)
適合動態組合協議、主機、連接埠、路徑:
// 協議、主機、路徑
URL url1 = new URL("http", "www.example.com", "/path/file.html");
// 協議、主機、連接埠、路徑
URL url2 = new URL("http", "www.example.com", 8080, "/path/file.html");
當 URL 格式錯誤或協議不支援時拋出,必須捕獲處理:
try {
URL url = new URL("invalid://url");
} catch (MalformedURLException e) {
// 處理錯誤
}
URL 類別提供存取器方法:
| 方法 | 回傳值 | 說明 |
|---|---|---|
getProtocol() | String | 協議識別符 |
getHost() | String | 主機名稱 |
getPort() | int | 連接埠號(未指定回傳 -1) |
getFile() | String | 檔案路徑(含查詢字串) |
getRef() | String | 錨點參考 |
import java.net.*;
public class ParseURL {
public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com:8080/path/file.html#section1");
System.out.println("protocol = " + url.getProtocol()); // http
System.out.println("host = " + url.getHost()); // www.example.com
System.out.println("file = " + url.getFile()); // /path/file.html
System.out.println("port = " + url.getPort()); // 8080
System.out.println("ref = " + url.getRef()); // section1
} catch (MalformedURLException e) {
System.err.println("MalformedURLException: " + e);
}
}
}
在 JDK 1.0.2 以前版本,getRef() 僅對以下建構子有效:
URL(String absoluteURL)URL(URL base, String relative)若使用元件組合建構子 URL(String protocol, String host, String file),getRef() 會回傳 null。建議統一使用字串或相對 URL 建構方式以確保錨點正確解析。
建立 URL 物件後,可透過 openConnection() 取得 URLConnection,進而開啟輸入串流讀取資料:
URL url = new URL("https://www.example.com/data.txt");
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
java.net.URL 是 Java 網路程式設計的高層抽象,封裝了協議解析、連線管理、資源定位等複雜細節。掌握 URL 建立、解析、連線讀取的完整流程,是開發網路爬蟲、API 客戶端、資源下載器等應用的基礎。實務上更常搭配 HttpURLConnection 或第三方函式庫(如 OkHttp、Apache HttpClient)處理複雜 HTTP 互動場景。