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

Java 取得網路文字資源工具類:支援 HTTP GET/POST 與 FTP

     編輯:Java 相關知識

功能概覽

提供統一介面透過 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 GEThttps://host/path?param=value"" (空字串)參數直接在 URL
HTTP POSThttps://host/pathparam=value&key=val自動設定 DoOutput、GBK 編碼
FTPftp://user:pass@host/path""支援匿名登入 (user:anonymous)

擴充建議

  • 加入連線/讀取逾時設定:conn.setConnectTimeout(5000); conn.setReadTimeout(10000);
  • 支援 HTTPS:需處理 SSLContext 信任策略
  • 回應編碼自動偵測:可從 Content-Type header 解析 charset
  • 例外拋出而非吞噬:依專案錯誤處理策略調整
  • 使用 HttpClient (Apache) 替代以支援連線池、重試、Redirect 等進階功能

本類別為教學示範用途,生產環境建議採用成熟 HTTP Client 函式庫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved