萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Java 網絡編程基礎:URL 類詳解、創建、解析與資源加載

Java java.net.URL 類是網絡編程的入口,封裝了統一資源定位符的解析、連接建立、數據流讀寫。本文系統講解 URL 結構、創建方式、相對/絕對路徑、組件拆解、異常處理及實際資源加載示例。

1. URL 結構拆解

protocol://host:port/path?query#fragment
  │         │    │    │      │       │
  │         │    │    │      │       └─ 片段標識(錨點)
  │         │    │    │      └─ 查詢參數
  │         │    │    └─ 資源路徑(文件路徑)
  │         │    └─ 端口號(可選,默認 80/443)
  │         └─ 主機名/IP
  └─ 協議(http, https, ftp, file, jar...)

2. 創建 URL 對象的四種構造器

// 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();

3. 核心獲取器方法

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()

4. 異常處理:MalformedURLException

try {
    URL url = new URL("htp://invalid"); // 協議拼寫錯誤
} catch (MalformedURLException e) {
    System.err.println("無效 URL 格式: " + e.getMessage());
    // 記錄日誌、拋出業務異常、使用默認值等
}

5. 實際資源加載:打開連接與讀取流

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();
    }
}

6. 加載圖片/資源到 Swing/JavaFX

// 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);

7. 相對 URL 與基礎 URL 解析規則(RFC 3986)

  • 相對路徑 ../ 向上一級目錄,./ 當前目錄。
  • 以 / 開頭為絕對路徑(相對於域根)。
  • 片段標識 #anchor 僅在客戶端使用,不發送給服務器。

8. 最佳實踐建議

  1. 優先使用 URI 類進行構建與解析(更嚴格符合 RFC 3986),最後 uri.toURL() 獲取 URL。
  2. 網絡操作必須在非 UI 線程執行(Swing 用 SwingWorker,JavaFX 用 Task,Android 用 OkHttp/Retrofit 協程)。
  3. 設置合理的連接/讀取超時,避免無限阻塞。
  4. 大文件下載使用 InputStream 分塊寫入磁盤,避免 OOM。
  5. 生產環境建議使用成熟 HTTP 客戶端庫(Apache HttpClient, OkHttp, Spring WebClient, Java 11+ HttpClient)替代原生 HttpURLConnection。

掌握 URL 類的創建、解析與流式讀取,是 Java 網絡編程的基石。

copyright © 萬盛學電腦網 all rights reserved