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

Java 使用 HttpURLConnection 發送 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);
        HttpURLConnection conn = (HttpURLConnection) 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(), StandardCharsets.UTF_8));
        String line;
        while ((line = in.readLine()) != null) result.append(line);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try { if (out != null) out.close(); } catch (IOException ignored) {}
        try { if (in != null) in.close(); } catch (IOException ignored) {}
    }
    return result.toString();
}

使用示例


String param = "name=zhangsan&age=20";
String resp = HttpUtil.sendPost("https://host/servlet", param);
// 遠程 Servlet 可用 request.getParameter("name") 獲取

注意

  • 參數格式 `name=value&name2=value2`,需 `URLEncoder.encode` 中文值。
  • 生產環境建議用 **Apache HttpClient** / **OkHttp** 替代原生 `HttpURLConnection` (連接池、重試、超時控制更完善)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved