統一資源定位符(URL,Uniform Resource Locator)是網際網路上資源的唯一地址。在 Java 程式設計中,java.net 套件提供了 URL 和 URLConnection 兩個核心類別,讓開發者能輕鬆實現網路資源的定位、連線與資料傳輸。
標準 URL 格式為:<協定>://<主機名:連接埠>/<路徑>/<檔案>
範例:https://www.example.com:8080/path/to/file.html
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。透過 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();
}
}
MalformedURLException 和 IOException掌握基礎 URL 操作後,可進一步學習: