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

Java 原生 HttpURLConnection 實現 GET/POST 請求工具類

     編輯:Java 程式設計入門

為什麼選擇原生 API?

零依賴、JDK 內建、適合輕量專案或受限環境。雖 API 較繁瑣,但封裝後即可複用。

核心工具類 HttpClient

package com.hongyuan.test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient {

    /** 發送 GET 請求 */
    public static String get(String path) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader in = null;
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuilder sb = new StringBuilder();
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) sb.append(line);
                return sb.toString();
            } else {
                throw new Exception("HTTP 錯誤碼: " + conn.getResponseCode());
            }
        } finally {
            closeQuietly(in);
            if (conn != null) conn.disconnect();
        }
    }

    /** 發送 POST 請求(表單/字串參數) */
    public static String post(String path, String params) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            out.print(params);
            out.flush();

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuilder sb = new StringBuilder();
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) sb.append(line);
                return sb.toString();
            } else {
                throw new Exception("HTTP 錯誤碼: " + conn.getResponseCode());
            }
        } finally {
            closeQuietly(in);
            closeQuietly(out);
            if (conn != null) conn.disconnect();
        }
    }

    private static void closeQuietly(Closeable c) {
        if (c != null) try { c.close(); } catch (IOException ignored) {}
    }

    public static void main(String[] args) throws Exception {
        // String res = get("https://localhost:3000/hello?hello=hello get");
        String res = post("https://localhost:3000/hello", "hello=hello post");
        System.out.println(res);
    }
}

關鍵配置說明

設定用途建議值
setConnectTimeout建立連線超時3000~5000 ms
setReadTimeout讀取資料超時5000~10000 ms
setRequestProperty設定 Header(Content-Type、User-Agent 等)視 API 文檔而定
setDoOutput(true)POST 必須開啟輸出流POST 時為 true

常見坑點與對策

  • 編碼不一致:統一指定 UTF-8,避免中文亂碼
  • 未關閉流導致連線洩漏:務必在 finally 中 disconnect()
  • 重定向處理:預設自動跟隨,若需手動控制用 setInstanceFollowRedirects(false)
  • HTTPS 憑證:自簽憑證需配置 TrustManager,生產環境請勿跳過驗證

擴展建議

  • 支援 JSON 請求體:Content-Type: application/json + ObjectMapper.writeValueAsString(obj)
  • 檔案上傳:multipart/form-data 需手動拼裝邊界,建議改用 Apache HttpClient 或 OkHttp
  • 連線池:原生無連線池,高併發場景請遷移至成熟 HTTP 客戶端庫
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved