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

Android 異步連網利器:Android Asynchronous Http Client 使用指南

編輯:關於 Android 程式設計

在 Android 上做網絡請求,早期幾乎繞不開 Apache HttpClient。Android Asynchronous Http Client(簡稱 Async HTTP)就是在它之上封裝出來的一層,目標只有一個:讓異步請求寫起來像同步一樣輕鬆。

它解決了什麼

核心思路是所有請求都在主線程之外發出,而回調邏輯通過 Android 的 Handler 消息機制,回到創建回調時的那個線程上執行——也就是說,你在 onSuccess() 裡可以直接更新 UI,不用自己折騰 runOnUiThread。

功能清單頗為實用:

  • 匿名回調處理異步響應,請求不佔用 UI 線程。
  • 內部使用線程池,限制並發以控制資源占用。
  • RequestParams 統一構造 GET/POST 參數。
  • 支持 multipart 文件上傳,無需引入額外第三方庫。
  • 體積極小,全部功能約 25KB。
  • 針對移動網絡不穩自動做智能重試。
  • 自動 gzip 解壓響應。
  • BinaryHttpResponseHandler 下載二進制數據(圖片等)。
  • JsonHttpResponseHandler 直接把響應解析成 JSON。
  • 持久化 Cookie,寫入 SharedPreferences。

值得一提的是,Instagram、Pinterest、Heyzap 等頭部應用都曾把它用在生產環境裡。

基本用法

從 GitHub 下載最新 jar 丟進工程的 libs/,導入包:

import com.loopj.android.http.*;

創建實例並發請求,就这么简单:

AsyncHttpClient client = new AsyncHttpClient();
client.get("https://www.google.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});

推薦做法:封裝一個靜態客戶端

實戰中更推薦把 client 收斂到一個類裡,讓業務代碼遠離細節。以 Twitter API 為例:

import com.loopj.android.http.*;

public class TwitterRestClient {
    private static final String BASE_URL = "https://api.twitter.com/1/";
    private static AsyncHttpClient client = new AsyncHttpClient();

    public static void get(String url, RequestParams params,
                           AsyncHttpResponseHandler responseHandler) {
        client.get(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params,
                            AsyncHttpResponseHandler responseHandler) {
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }

    private static String getAbsoluteUrl(String relativeUrl) {
        return BASE_URL + relativeUrl;
    }
}

之後業務層調用起來就非常乾淨:

class TwitterRestClientUsage {
    public void getPublicTimeline() throws JSONException {
        TwitterRestClient.get("statuses/public_timeline.json", null,
            new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(JSONArray timeline) {
                    JSONObject firstEvent = timeline.get(0);
                    String tweetText = firstEvent.getString("text");
                    System.out.println(tweetText);
                }
            });
    }
}

持久化 Cookie

庫裡自帶 PersistentCookieStore,實現了 Apache 的 CookieStore 接口,並把 Cookie 自動存進 SharedPreferences。做登錄態保持時非常好用——用戶殺掉 App 再回來,依然是登錄狀態。

AsyncHttpClient myClient = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);

想自己塞 Cookie 也很直觀:

BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);

RequestParams:GET/POST 參數與文件上傳

RequestParams 支持多種構造方式:

// 空對象後逐個添加
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");

// 單個參數
RequestParams params = new RequestParams("single", "value");

// 從已有 Map 構造
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);

上傳文件時,InputStream、File、字節數組三種形式都支持:

// InputStream
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");

// File
File myFile = new File("/path/to/file.png");
params.put("profile_picture", myFile);

// 字節數組
byte[] myByteArray = blah;
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

下載二進制數據

圖片、音頻之類的非文本內容用 BinaryHttpResponseHandler,可以順手限制允許的 Content-Type:

AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get("https://example.com/file.png", new BinaryHttpResponseHandler(allowedContentTypes) {
    @Override
    public void onSuccess(byte[] fileData) {
        // 處理文件字節
    }
});

HTTP Basic 認證

有些接口需要賬號密碼,用 setBasicAuth() 提供憑證即可。默認作用域是任意 host、port 和 realm:

AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username", "password/token");
client.get("https://example.com");

更推薦指定精確的認證作用域:

AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username", "password",
        new AuthScope("example.com", 80, AuthScope.ANY_REALM));
client.get("https://example.com");

從源碼構建

克隆倉庫後,把 local.properties.dist 複製為 local.properties,修改其中的 sdk.dir 指向本機 Android SDK 位置,然後執行:

ant package

產物名為 android-async-http-version.jar。

許可與致謝

本庫基於對 Android 友好的 Apache License 2.0 發布。作者 James Smith 是舊金山的一位創業者與開發者,Bugsnag 聯合創始人,2009 至 2012 年間擔任 Heyzap 的 CTO;Marek Sebera 自 1.4.4 版本起接手維護,Micah Fivecoate 則是 RequestParams 的主要貢獻者。此外還受益於 Droid Fu 項目的重試策略、Rafael Sanches 的 SimpleMultipartEntity 原始代碼等社區成果。

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