標準 JDK HttpURLConnection 實作無依賴 HTTP 客戶端,支援 GET/POST、Header 設定、超時控制、編碼處理、資源自動釋放。
import java.io.*;
import java.net.*;
import java.util.*;
public class HttpRequest {
/** 發送 GET 請求 */
public static String sendGet(String url, String param) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlStr = url + (param.isEmpty() ? "" : "?" + param);
URL realUrl = new URL(urlStr);
URLConnection conn = realUrl.openConnection();
// 通用請求頭
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.connect();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) result.append(line);
} catch (Exception e) {
System.err.println("GET 請求異常: " + e);
e.printStackTrace();
} finally {
closeQuietly(in);
}
return result.toString();
}
/** 發送 POST 請求 */
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// POST 必須設定
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) result.append(line);
} catch (Exception e) {
System.err.println("POST 請求異常: " + e);
e.printStackTrace();
} finally {
closeQuietly(out);
closeQuietly(in);
}
return result.toString();
}
private static void closeQuietly(Closeable c) {
if (c != null) try { c.close(); } catch (IOException ignored) {}
}
}
// GET
String getResp = HttpRequest.sendGet("https://api.example.com/users", "id=123&name=test");
// POST (application/x-www-form-urlencoded)
String postResp = HttpRequest.sendPost("https://api.example.com/login", "username=admin&password=123456");
// POST JSON (需額外設定 Content-Type)
/*
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonString.getBytes("UTF-8"));
}
*/
InputStreamReader(conn.getInputStream(), "UTF-8") 避免中文亂碼。conn.setConnectTimeout(5000); // 連線 5 秒
conn.setReadTimeout(10000); // 讀取 10 秒
connection: Keep-Alive 復用 TCP 連線,降低延遲。finally 區塊確保流關閉,JDK 7+ 建議 try-with-resources。| 客戶端 | 特點 | Maven 依賴 |
|---|---|---|
| Apache HttpClient 4.5+ | 功能最完整、連線池、重試、攔截器、異步支援 | org.apache.httpcomponents:httpclient |
| OkHttp 3/4 | 現代化、HTTP/2、連線池、Kotlin 友善、Android 首選 | com.squareup.okhttp3:okhttp |
| Java 11+ HttpClient | 標準庫、HTTP/2、WebSocket、CompletableFuture 異步 | 無 (java.net.http) |
CloseableHttpClient httpClient = HttpClients.custom()
.setMaxConnTotal(200)
.setMaxConnPerRoute(50)
.evictIdleConnections(30, TimeUnit.SECONDS)
.build();
HttpGet get = new HttpGet("https://api.example.com/users?id=123");
try (CloseableHttpResponse resp = httpClient.execute(get)) {
String body = EntityUtils.toString(resp.getEntity(), "UTF-8");
}