Python:HTTPConnection.request(method, url, body=None, headers={})
Java 需手動拼裝:Method、URL、Headers、Body。
URL 對象,openConnection() 獲取 HttpURLConnection。setRequestMethod(method) 設置 HTTP 方法。Map<String, String> headers,調用 setRequestProperty(k, v) 逐個寫入 Header。setDoOutput(true) 開啟輸出流,獲取 OutputStream 寫入 Body(字節數組/字符串)。getResponseCode() 判斷狀態,getInputStream() 讀取響應。public static String httpRequest(String method, String url,
Map<String, String> headers,
byte[] body, String charset) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) {
conn.setRequestProperty(e.getKey(), e.getValue());
}
}
if (body != null && body.length > 0) {
try (OutputStream os = conn.getOutputStream()) {
os.write(body);
}
}
int code = conn.getResponseCode();
InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
return new String(is.readAllBytes(), charset);
}
setRequestProperty 可多次調用同一 Key,符合 HTTP 多值 Header 標準。conn.setConnectTimeout(5000); conn.setReadTimeout(10000);。掌握上述模板,即可在 Java 中靈活復刻 Python 的四參數 HTTP 請求能力。