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

Android Asynchronous Http Client:回呼式非同步 HTTP 用戶端庫

編輯:關於 Android 程式設計

Android Asynchronous Http Client

A Callback-Based Http Client Library for Android

下載版本 1.4.2(最新版),或 fork me on github。

概觀

這是一個基於 Apache HttpClient 建構的非同步、回呼式 HTTP 用戶端。所有請求都在 App 的主 UI 線程之外發出,而回呼邏輯則透過 Android 的 Handler 訊息傳遞機制,在建立回呼的同一條線程上執行。

主要特性

  • 發送非同步 HTTP 請求,在匿名回呼中處理回應
  • 請求在 UI 線程之外執行
  • 使用執行緒池限制同時資源的用量
  • GET/POST 參數建構器(RequestParams)
  • 支援多部分檔案上傳,無需額外套件
  • 體積極小,全部僅約 25kb
  • 針對不穩定的行動網路自動智慧重試
  • 自動 gzip 回應解碼
  • 以 BinaryHttpResponseHandler 下載二進位檔案
  • 以 JsonHttpResponseHandler 內建 JSON 解析
  • 持久化 Cookie 儲存,存入 App 的 SharedPreferences

安裝與基本用法

從 github 下載最新的 .jar 檔並放入 App 的 libs/ 資料夾,然後匯入 http 套件:

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

推薦用法:建立靜態 Http Client

可建立一個帶靜態存取器的方法類別,方便與 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;
    }
}

如此一來在程式中操作 API 就非常直觀:

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

持久化 Cookie 儲存

PersistentCookieStore 是 Apache HttpClient CookieStore 介面的實作,會自動把 Cookie 存到裝置的 SharedPreferences。這對以 Cookie 管理登入工作階段非常有用,使用者即使關閉再重開 App 仍能保持登入:

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

使用 RequestParams 添加 GET/POST 參數

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

使用 RequestParams 上傳檔案

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

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

// 上傳 byte 陣列
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

使用 BinaryHttpResponseHandler 下載二進位資料

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 Auth 憑證

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

// 更精確的驗證範圍(推薦)
client.setBasicAuth("username", "password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));
client.get("https://example.com");

從源碼建構

先 clone android-async-http 的 github 倉庫,將 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。

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