Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 以同步方式封裝 HTTP GET 與 POST 請求的工具類

編輯:關於 Android 程式設計

做客戶端開發時,最基礎也最高頻的需求就是跟伺服器交換數據。下面這份 ApacheHttpClient 工具類把 GET 與 POST 兩種同步請求都封裝好了,簡單、直接,複用起來很方便。

/**
 * 以同步方式發送 Http 請求
 */
public class ApacheHttpClient {

    /**
     * 發送 GET 請求
     * @param uri 請求地址
     * @return 伺服器響應內容
     */
    public String httpGet(String uri) {
        String response = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(uri);
        try {
            // execute 方法會發送請求並回傳 HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                response = EntityUtils.toString(httpResponse.getEntity());
            } else {
                response = "返回碼:" + statusCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 以 POST 方式發送請求
     * @param uri    請求地址
     * @param params 參數,POST 需用 NameValuePair 列表儲存
     * @return 伺服器響應內容
     */
    public String httpPost(String uri, List<NameValuePair> params) throws Exception {
        String response = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri);
        try {
            // 設定請求參數,注意顯式指定 UTF-8,避免中文亂碼
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                response = EntityUtils.toString(httpResponse.getEntity());
            } else {
                response = "返回碼:" + statusCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}

使用說明

GET 只要傳網址;POST 需要把參數裝進 List<NameValuePair>:

List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("username", "admin"));
params.add(new BasicNameValuePair("password", "123456"));
String result = new ApacheHttpClient().httpPost(url, params);

幾點必須注意的事

  • 不能在主執行緒發網路請求。Honeycomb 之後系統直接禁止,會拋 NetworkOnMainThreadException。請用 AsyncTask、Thread + Handler、RxJava 或 Kotlin 協程把請求放到子執行緒,結果再切回主執行緒更新 UI。
  • 記得補權限。AndroidManifest.xml 中需要 <uses-permission android:name="android.permission.INTERNET" />。
  • 字元編碼要顯式指定。GET 端解析響應時建議寫成 EntityUtils.toString(entity, "UTF-8"),否則中文容易變亂碼。
  • DefaultHttpClient 與 HttpClient 已被標記為 deprecated。新專案建議改用 HttpURLConnection、OkHttp 或 Retrofit;這份代碼的價值在於把「請求—狀態碼判斷—解析響應」的流程講清楚。
  • 異常不要只 printStackTrace。網路環境複雜,超時、斷網、DNS 失敗都會拋異常,記得設定 Timeout 並把錯誤回傳給上層處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved