零依賴、JDK 內建、適合輕量專案或受限環境。雖 API 較繁瑣,但封裝後即可複用。
HttpClientpackage 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)TrustManager,生產環境請勿跳過驗證Content-Type: application/json + ObjectMapper.writeValueAsString(obj)multipart/form-data 需手動拼裝邊界,建議改用 Apache HttpClient 或 OkHttp