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

Android 原生 HttpURLConnection 實現 GET/POST 請求的完整封裝工具類

     編輯:程式設計疑難解答

工具類代碼


public class HttpUtil {
    private static final int TIMEOUT = 10000;

    // GET 請求
    public static String get(String urlString) throws IOException {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);
            conn.setRequestProperty("Accept", "application/json");
            return readResponse(conn);
        } finally {
            if (conn != null) conn.disconnect();
        }
    }

    // POST 請求(表單/JSON)
    public static String post(String urlString, String jsonBody) throws IOException {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Accept", "application/json");
            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonBody.getBytes("UTF-8"));
            }
            return readResponse(conn);
        } finally {
            if (conn != null) conn.disconnect();
        }
    }

    // POST 表單
    public static String postForm(String urlString, Map params) throws IOException {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry e : params.entrySet()) {
            if (sb.length() > 0) sb.append('&');
            sb.append(URLEncoder.encode(e.getKey(), "UTF-8"))
              .append('=')
              .append(URLEncoder.encode(e.getValue(), "UTF-8"));
        }
        return post(urlString, sb.toString()); // 實際應設置 Content-Type: application/x-www-form-urlencoded
    }

    private static String readResponse(HttpURLConnection conn) throws IOException {
        int code = conn.getResponseCode();
        InputStream is = (code >= 400) ? conn.getErrorStream() : conn.getInputStream();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) sb.append(line);
            return sb.toString();
        }
    }
}

使用示例


// 異步調用(必須在子線程)
new Thread(() -> {
    try {
        String json = HttpUtil.get("https://api.example.com/users/1");
        runOnUiThread(() -> parseAndShow(json));
    } catch (IOException e) { e.printStackTrace(); }
}).start();

注意事項

  • Android 9+ 需在 AndroidManifest.xml 配置 android:usesCleartextTraffic="true" 允許 HTTP(生產必須 HTTPS)。
  • 生產環境建議遷移至 OkHttp 或 Retrofit,支持連接池、攔截器、協程、自動重試等企業級特性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved