提供統一介面透過 HTTP (GET/POST) 或 FTP 協定取得遠端文字資源,支援中文編碼 (GBK) 處理,適合簡易爬蟲、API 呼叫、檔案下載等場景。
import java.io.*;
import java.net.*;
import java.util.*;
public class HttpFetcher {
/**
* 取得遠端資源內容
* @param urlString 目標 URL (支援 https://, ftp://)
* @param postParam POST 參數字串 (如 "action=login&user=admin"),空字串表示 GET
* @return 回應內容字串,失敗返回空字串
*/
public static String openUrl(String urlString, String postParam) {
StringBuffer document = new StringBuffer();
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
// POST 模式
if (postParam != null && !postParam.trim().isEmpty()) {
conn.setDoOutput(true);
try (OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "GBK")) {
out.write(postParam);
out.flush();
}
}
// 讀取回應
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
document.append(line).append("\n");
}
}
} catch (MalformedURLException e) {
System.err.println("URL 格式錯誤: " + urlString);
} catch (IOException e) {
System.err.println("連線失敗: " + urlString + " - " + e.getMessage());
}
return document.toString();
}
// 測試主程式
public static void main(String[] args) {
// POST 範例:手機歸屬地查詢
System.out.println(openUrl("https://www.ip138.com:8080/search.asp",
"action=mobile&mobile=13910000000&B1=查詢"));
// GET 範例
System.out.println(openUrl("https://www.ip138.com:8080/search.asp?action=mobile&mobile=13910000000&B1=查詢", ""));
// FTP 範例 (需帳密)
System.out.println(openUrl("ftp://user:pass@192.168.0.1/book/jdk.txt", ""));
}
}
| 協定 | urlString 格式 | postParam | 備註 |
|---|---|---|---|
| HTTP GET | https://host/path?param=value | "" (空字串) | 參數直接在 URL |
| HTTP POST | https://host/path | param=value&key=val | 自動設定 DoOutput、GBK 編碼 |
| FTP | ftp://user:pass@host/path | "" | 支援匿名登入 (user:anonymous) |
conn.setConnectTimeout(5000); conn.setReadTimeout(10000);Content-Type header 解析 charsetHttpClient (Apache) 替代以支援連線池、重試、Redirect 等進階功能本類別為教學示範用途,生產環境建議採用成熟 HTTP Client 函式庫。