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

Android Asynchronous Http Client:回呼式非同步網路請求庫

編輯:關於 Android 程式設計

概觀

AHC 建立在 Apache 的 HttpClient 之上,把整個網路請求過程移出 UI 執行緒,回呼則透過 Handler 派送回主執行緒。它也可以在 Service 或背景程式中使用,會自動辨識並在對應的 Context 上處理回呼。

主要特性

  • 非同步送出 HTTP 請求,於回呼函式中處理結果
  • 請求過程不佔用 UI 執行緒,並以執行緒池管理並發數
  • 支援 GET / POST,請求參數獨立設定,不依賴其他函式庫
  • 可序列化 JSON 資料上傳
  • 自動處理重定向,並依網路連線狀況智慧調整重試次數
  • 體積僅約 90K
  • 支援 gzip 壓縮傳輸
  • 內建 JsonHttpResponseHandler 解析 JSON;FileAsyncHttpResponseHandler 直接把回應存成檔案;BinaryHttpResponseHandler 處理二進位協議
  • BaseJsonHttpResponseHandler 可搭配 Jackson、Gson 等反序列化庫
  • 支援 SAX 解析(SaxAsyncHttpResponseHandler)
  • 支援多語言多編碼,不限 UTF-8
  • Cookie 自動持久化到 SharedPreferences

使用者名單裡有 Instagram、Pinterest 等。

基本用法

Maven 依賴:

<dependency>
    <groupId>com.loopj.android</groupId>
    <artifactId>android-async-http</artifactId>
    <version>1.4.5</version>
</dependency>

建立 AsyncHttpClient 並發送請求:

client.get("https://www.google.com", new AsyncHttpResponseHandler() {
    @Override
    public void onStart() {
        // 請求開始前呼叫
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // HTTP 200 OK
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // 4XX,例如 401 / 403 / 404
    }

    @Override
    public void onRetry(int retryNo) {
        // 請求被重試時呼叫
    }
});

推薦做法:封裝一個靜態 Client

實務上不要到處 new,而是開一個網路工具類,共用一個全域靜態的 AsyncHttpClient:

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;
    }
}

之後在需要的地方直接呼叫:

import org.json.*;
import com.loopj.android.http.*;

class TwitterRestClientUsage {
    public void getPublicTimeline() throws JSONException {
        TwitterRestClient.get("statuses/public_timeline.json", null,
            new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    // 若回應是 JSONObject 而非預期的 JSONArray
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
                    JSONObject firstEvent = timeline.getJSONObject(0);
                    String tweetText = firstEvent.getString("text");
                    System.out.println(tweetText);
                }
            });
    }
}

用 PersistentCookieStore 保持登入狀態

這個庫內建 PersistentCookieStore,是 Apache HttpClient 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 帶參數

// 1. 空的,逐筆加
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");

// 2. 一對一建立
RequestParams params2 = new RequestParams("single", "value");

// 3. 從 Map 建立
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params3 = new RequestParams(paramMap);

上傳檔案

RequestParams 支援多媒體上傳,三種形式:

// InputStream
InputStream myInputStream = ...;
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 陣列
byte[] myByteArray = ...;
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

下載二進位檔案

AsyncHttpClient client = new AsyncHttpClient();
client.get("https://example.com/file.png", new FileAsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, File response) {
        // 直接使用 response 這個 File
    }
});

加入基本認證

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

// 若要自訂範圍
client.setBasicAuth(username, password,
        new AuthScope("example.com", 80, AuthScope.ANY_REALM));

官方文件:https://loopj.com/android-async-http/
GitHub:https://github.com/loopj/android-async-http

最後補一句現況:這個庫已多年未更新,且依賴的 Apache HttpClient 在 Android 5.0 之後已被移除。新專案建議改用 OkHttp 或 Retrofit,它們在攔截器、連線池與非同步模型上都更成熟。

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