首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 實現 Python HTTPConnection.request 四參數請求的完整方案

     編輯:程式設計疑難解答

需求對照

Python:HTTPConnection.request(method, url, body=None, headers={})
Java 需手動拼裝:Method、URL、Headers、Body。

核心步驟

  1. 創建 URL 對象,openConnection() 獲取 HttpURLConnection。
  2. setRequestMethod(method) 設置 HTTP 方法。
  3. 遍歷 Map<String, String> headers,調用 setRequestProperty(k, v) 逐個寫入 Header。
  4. setDoOutput(true) 開啟輸出流,獲取 OutputStream 寫入 Body(字節數組/字符串)。
  5. 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);
}

關鍵差異提示

  • Java 無內置 multipart 構建,需手動拼接 boundary 或引用 Apache HttpClient / OkHttp。
  • setRequestProperty 可多次調用同一 Key,符合 HTTP 多值 Header 標準。
  • 超時設置:conn.setConnectTimeout(5000); conn.setReadTimeout(10000);。

掌握上述模板,即可在 Java 中靈活復刻 Python 的四參數 HTTP 請求能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved