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

使用 HttpClient 框架發送 GET 請求

編輯:關於 Android 程式設計

除了 HttpURLConnection,Apache HttpClient 也是早期 Android 上常見的 HTTP 方案。它的介面抽象度更高,把「開啟瀏覽器、輸入網址、按下 Enter」這三個動作映射成 DefaultHttpClient、HttpGet 與 execute(),寫起來很好理解。

/**
 * 以 HttpClient 的 GET 方式發送請求
 *
 * @param username 使用者名稱
 * @param password 密碼
 * @return null 表示請求路徑有問題,text 為請求取得的資料
 */
public static String httpclientGet(String username, String password) {
    try {
        // 1. 建立一個客戶端,相當於打開瀏覽器
        HttpClient client = new DefaultHttpClient();

        // 2. 組出網址,指定請求方式為 GET
        String path = "https://172.22.64.156:8080/0001AndroidWebService/LoginServlet?username="
                + URLEncoder.encode(username)
                + "&password="
                + URLEncoder.encode(password);
        HttpGet get = new HttpGet(path);

        // 3. 送出請求,相當於按下 Enter
        HttpResponse response = client.execute(get);

        // 取得回應狀態碼
        int code = response.getStatusLine().getStatusCode();
        if (code == 200) {
            InputStream is = response.getEntity().getContent();
            String text = StreamUtil.readStream(is);
            return text;
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

該知道的前提

Apache HttpClient 在 Android 上已被官方標記為不建議使用:從 Android 6.0(API 23)起,它自平台中被移除,若仍要使用必須自行在 build.gradle 宣告 useLibrary 'org.apache.http.legacy' 或手動引入 jar 檔。新專案請改用 HttpURLConnection、OkHttp 或 Retrofit。

讀懂這段程式碼仍有意義,因為它清楚示範了 HTTP 請求的三個必要環節:客戶端、請求物件、回應處理。這套心智模型換到任何 HTTP 函式庫上都成立。

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