Java 原生提供 HttpURLConnection,輕量零依賴;Apache HttpClient 功能豐富、API 友善。兩者皆可發送 GET/POST 請求並處理回應。本文提供兩套完整、可直接複製使用的工具類。
Maven 依賴:org.apache.httpcomponents:httpclient:4.5.14
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;
public class HttpClientUtil {
/** 發送 POST 表單請求
* @param url 目標 URL
* @param params 參數鍵值對
* @return 回應字串
*/
public static String post(String url, List params) {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // 編碼自行調整
// 設定超時 (可選)
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(10000)
.build();
httpPost.setConfig(config);
try (CloseableHttpResponse response = client.execute(httpPost)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
}
}
} catch (Exception e) {
throw new RuntimeException("HTTP POST 失敗: " + url, e);
}
return null;
}
// 使用範例
public static void main(String[] args) {
List params = new ArrayList<>();
params.add(new BasicNameValuePair("user", "admin"));
params.add(new BasicNameValuePair("action", "login"));
String result = post("https://api.example.com/endpoint", params);
System.out.println("回應:" + result);
}
}
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUrlConnectionUtil {
/** 通用請求方法
* @param urlString 目標 URL
* @param method "GET" 或 "POST"
* @param params 參數 Map (GET 會拼接到 URL,POST 寫入 Body)
* @return 回應字串
*/
public static String request(String urlString, String method, Map params) {
HttpURLConnection conn = null;
try {
// 處理 GET 參數拼接
String url = urlString;
if ("GET".equalsIgnoreCase(method) && params != null && !params.isEmpty()) {
url += (url.contains("?") ? "&" : "?") + buildQueryString(params);
}
URL urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
conn.setRequestProperty("User-Agent", "Java-HttpClient/1.0");
// POST 寫入 Body
if ("POST".equalsIgnoreCase(method) && params != null && !params.isEmpty()) {
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(buildQueryString(params).getBytes(StandardCharsets.UTF_8));
}
}
// 讀取回應
int code = conn.getResponseCode();
InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line);
return sb.toString();
}
} catch (Exception e) {
throw new RuntimeException("HTTP 請求失敗: " + urlString, e);
} finally {
if (conn != null) conn.disconnect();
}
}
private static String buildQueryString(Map params) {
StringBuilder sb = new StringBuilder();
for (Map.Entry e : params.entrySet()) {
if (sb.length() > 0) sb.append('&');
sb.append(e.getKey()).append('=').append(e.getValue());
}
return sb.toString();
}
}
| 場景 | 推薦 | 理由 |
|---|---|---|
| 簡單專案、不想引入第三方 jar | HttpURLConnection | JDK 內建、零依賴、啟動快 |
| 需支援連線池、重試、攔截器、多部分上傳 | HttpClient / OkHttp | API 豐富、效能優、社群活躍 |
| 現代專案 (Spring Boot 2.1+) | WebClient / RestTemplate | 非阻塞、聲明式、整合度高 |
HttpClient 用 try-with-resources;HttpURLConnection 必須 disconnect()TrustManager 或信任全部 (僅測試用)根據專案需求選擇合適工具,並建立統一的 HTTP 工具類,即可輕鬆應對各類介面串接。