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

Java 網路程式設計:URL 類與 URLConnection 完整應用指南

     編輯:Java 相關知識

Java 中的 URL 處理核心概念

統一資源定位符(URL,Uniform Resource Locator)是網際網路上資源的唯一地址。在 Java 程式設計中,java.net 套件提供了 URL 和 URLConnection 兩個核心類別,讓開發者能輕鬆實現網路資源的定位、連線與資料傳輸。

URL 結構解析

標準 URL 格式為:<協定>://<主機名:連接埠>/<路徑>/<檔案>

  • 協定:傳輸協定(如 HTTP、FTP)
  • 主機名:伺服器的網域名稱或 IP 位址
  • 連接埠:伺服器監聽的連接埠號(可省略,使用預設值)
  • 路徑與檔案:資源在伺服器上的具體位置

範例:https://www.example.com:8080/path/to/file.html

URL 類別的基本操作

URL 類別代表一個網路資源,常用建構子為 URL(String spec)。建立 URL 物件時可能拋出 MalformedURLException,因此必須包裹在 try-catch 區塊中:

URL myURL;
try {
    myURL = new URL("https://www.example.com:80/");
} catch (MalformedURLException e) {
    System.out.println("無效的 URL: " + e.getMessage());
}

URLConnection 實現網路通訊

若需進行資料收發,需使用 URLConnection。透過 URL.openConnection() 取得連線物件,再呼叫 connect() 建立實際連線:

URL url = new URL("https://www.example.com/");
URLConnection conn = url.openConnection();
conn.connect(); // 建立連線

核心串流方法

  • getInputStream():取得輸入串流,讀取伺服器回應資料
  • getOutputStream():取得輸出串流,發送請求資料

完整範例:讀取網頁內容

以下程式示範如何透過 URL 讀取網頁原始碼並顯示於文字區域:

import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class WebPageReader extends JFrame implements ActionListener {
    private JTextField urlField = new JTextField(30);
    private JTextArea displayArea = new JTextArea();
    private JButton btnLoad = new JButton("讀取網頁");

    public WebPageReader() {
        super("網頁內容讀取器");
        setLayout(new BorderLayout());
        JPanel topPanel = new JPanel();
        topPanel.add(urlField);
        topPanel.add(btnLoad);
        add(topPanel, BorderLayout.NORTH);
        add(new JScrollPane(displayArea), BorderLayout.CENTER);
        btnLoad.addActionListener(this);
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        readWebPage(urlField.getText().trim());
    }

    private void readWebPage(String urlStr) {
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.connect();
            
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
                displayArea.setText("");
                String line;
                while ((line = reader.readLine()) != null) {
                    displayArea.append(line + "\n");
                }
            }
        } catch (MalformedURLException ex) {
            JOptionPane.showMessageDialog(this, "URL 格式錯誤: " + ex.getMessage());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "讀取失敗: " + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        new WebPageReader();
    }
}

關鍵注意事項

  1. 例外處理:網路操作必須處理 MalformedURLException 和 IOException
  2. 資源釋放:使用 try-with-resources 自動關閉串流,避免資源洩漏
  3. 編碼指定:建議明確指定字元編碼(如 UTF-8)以避免亂碼
  4. 連線逾時:實際專案中應設定連線與讀取逾時時間

進階應用方向

掌握基礎 URL 操作後,可進一步學習:

  • HTTP 協定細節與請求標頭控制
  • HTTPS 憑證驗證與 SSLContext 設定
  • 連線池技術提升高併發效能
  • 非同步 HTTP 客戶端(如 HttpClient、OkHttp)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved