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

Android 網路請求入門:HttpGet 與 HttpPost 的三步驟用法

編輯:關於 Android 程式設計

Android SDK 內建了 Apache HttpClient 模組,早期幾乎所有 App 的網路溝通都建立在它之上。這裡有個容易混淆的細節:Android 採用的是 HttpClient 4.0,套件名稱為 org.apache.http.*,而非常見的 Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。上網查資料時若直接複製 3.x 的範例,會發現不少類別與方法對不上,原因就在此。

兩個核心類別

HttpClient 最常搭配 HttpGet 與 HttpPost 使用,分別對應 HTTP 的 GET 與 POST 方法。不論選哪一個,流程都是同樣的三步:

  1. 建立 HttpGet 或 HttpPost 物件,把請求的 URL 透過建構子傳入。
  2. 呼叫 DefaultHttpClient.execute() 送出請求,取得 HttpResponse 物件。
  3. 透過 HttpResponse.getEntity() 取得回應內容並做後續處理。

若使用 POST,還需在第二步之前多一個動作:以 setEntity() 設定請求參數,參數必須包裝成 NameValuePair 的清單。

GET 的實作

// HttpGet 方式請求
public static void requestByHttpGet() throws Exception {
    String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";

    // 1. 建立 HttpGet 物件
    HttpGet httpGet = new HttpGet(path);

    // 2. 送出請求
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResp = httpClient.execute(httpGet);

    // 3. 處理回應
    if (httpResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
        Log.i(TAG_HTTPGET, "HttpGet 請求成功,回傳內容如下:");
        Log.i(TAG_HTTPGET, result);
    } else {
        Log.i(TAG_HTTPGET, "HttpGet 請求失敗");
    }
}

另一種較精簡的寫法,把請求物件建立與 execute 串在一起,並在失敗時主動中止連線:

public String doGet() {
    String uriAPI = "https://XXXXX?str=I+am+get+String";
    String result = "";

    HttpGet httpRequst = new HttpGet(uriAPI);

    try {
        // HttpGet 是 HttpUriRequest 的子類
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
            // 移除回傳字串中的 "\r",否則顯示時尾端會出現一個小方塊
            result = result.replaceAll("\r", "");
        } else {
            httpRequst.abort();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        result = e.getMessage().toString();
    } catch (IOException e) {
        e.printStackTrace();
        result = e.getMessage().toString();
    }
    return result;
}

POST 的實作

POST 的差異在於參數不放在網址列,而是透過 UrlEncodedFormEntity 編碼後塞進 entity。字元集務必明確指定為 UTF-8,否則中文參數會出現亂碼。

public String doPost() {
    String uriAPI = "https://XXXXXX";   // POST 的參數不寫在網址上
    String result = "";

    // 1. 建立 HttpPost 物件
    HttpPost httpRequst = new HttpPost(uriAPI);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("str", "I am Post String"));

    try {
        httpRequst.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

        HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        result = e.getMessage().toString();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        result = e.getMessage().toString();
    } catch (IOException e) {
        e.printStackTrace();
        result = e.getMessage().toString();
    }
    return result;
}

若偏好一次寫完、不做封裝,可以參考這個版本:

// HttpPost 方式請求
public static void requestByHttpPost() throws Exception {
    String path = "https://reg.163.com/logins.jsp";

    HttpPost httpPost = new HttpPost(path);

    // POST 參數
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("id", "helloworld"));
    params.add(new BasicNameValuePair("pwd", "android"));

    // 指定字元集
    HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
    httpPost.setEntity(entity);

    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResp = httpClient.execute(httpPost);

    if (httpResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
        Log.i(TAG_HTTPGET, "HttpPost 請求成功,回傳內容如下:");
        Log.i(TAG_HTTPGET, result);
    } else {
        Log.i(TAG_HTTPGET, "HttpPost 請求失敗");
    }
}

幾個實務上會踩到的坑

記得加網路權限。AndroidManifest.xml 中必須宣告 <uses-permission android:name="android.permission.INTERNET" />,否則會直接抛出 UnknownHostException。

不能在主執行緒上請求。Android 3.0(Honeycomb)以後強制執行的 StrictMode 會攔截主執行緒的網路 I/O 並丟出 NetworkOnMainThreadException。上述範例都應包在 AsyncTask、自建 Thread 或(現代做法)ExecutorService/Kotlin 協程之中執行,再把結果回傳主執行緒更新 UI。

記得釋放連線與串流。用完 HttpEntity 應呼叫 consumeContent()(4.0 版)或關閉 InputStream,否則連線池會被佔满導致後續請求阻塞。

現行專案的建議。Apache HttpClient 已在 Android 5.1(API 22)之後被標記為 deprecated 並於後續版本移除,Google 官方推薦改用 HttpURLConnection,或直接使用 OkHttp、Retrofit 這類成熟函式庫。若你是在維護老專案,本文的邏輯仍完全適用;若是新專案,建議把「三步驟」的心智模型帶到新工具上——建立請求、送出、解析回應——概念並沒有改變。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved