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

Android 網絡框架 android-async-http 使用指南

編輯:關於 Android 程式設計

這是 Android 網絡框架系列的最後一篇。前面我們聊過 Volley 與 Picasso,這次把第三方庫 android-async-http 收進口袋,並在結尾處整理如何在開發中選用與駕馭第三方框架。

一、Android Asynchronous Http Client 簡介

android-async-http 是對 HttpClient 的頂層封裝,所有 Request 都運行在獨立於 UI 線程的其他線程中,而回調的處理方式又與 Handler 發送 message 的邏輯一致,你也可以讓它跑在 Service 或背景線程裡。

主要特點:

  • 異步 HTTP 請求,匿名回調響應函數
  • 在非 UI 線程中發送 Request
  • 使用線程池管理並限制並發資源
  • 可自定義 GET/POST 參數
  • 支援多種檔案上傳方式與 JSON 數據上傳
  • 內建 Request 重試機制
  • 可解析多種數據格式,支援持久化 Cookie 與 SAX 解析
  • 支援多種編碼格式,不限於 UTF-8

二、基本用法

與所有第三方庫一樣,先將 android-async-http.jar 加入專案的 libs 目錄並 Add As Library;若是 clone 的專案,則需先編譯成 jar 包:

android update project -p <path> jar

建立一個 AsyncHttpClient 實例後即可發起請求:

AsyncHttpClient client = new AsyncHttpClient();
client.get("https://www.baidu.com", new AsyncHttpResponseHandler() {
    @Override
    public void onStart() {
        // Request 發起前調用
    }
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // 正確響應時調用,statusCode = 200
    }
    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // 未正確響應時調用
    }
    @Override
    public void onRetry(int retryNo) {
        // 重試請求時調用
    }
});

推薦做法:建立一個 static Client 類統一持有實例,方便全域呼叫,這與 Volley 的思路一致:

public class MyClient {
    private static final String BASE_URL = "https://www.baidu.com";
    private static AsyncHttpClient client = new AsyncHttpClient();

    public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHand) {
        client.get(url, params, responseHand);
    }
    public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHand) {
        client.post(url, params, responseHand);
    }
}
// 呼叫:MyClient.get(url, params, new AsyncHttpResponseHandler(){ ... });

三、Cookie 的存儲

透過 PersistentCookieStore 可自動把 Cookie 存進 SharedPreferences,常用於保存登入資訊:

AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore cookieStore = new PersistentCookieStore(context);
client.setCookieStore(cookieStore);

BasicClientCookie myCookie = new BasicClientCookie("cookieuser", "hh");
myCookie.setVersion(1);
myCookie.setDomain("www.my.com");
myCookie.setPath("/");
client.addCookie(myCookie);

四、添加 GET/POST 參數

使用 RequestParams 類,有多種建立方式:

RequestParams params = new RequestParams("username", "coder");
// 或
RequestParams params = new RequestParams();
params.put("username", "coder");
// 或以 Map 建立
HashMap<String, String> map = new HashMap<String, String>();
map.put("username", "coder");
RequestParams params = new RequestParams(map);
client.get(url, params, new AsyncHttpResponseHandler(){ ... });

五、上傳檔案

以輸入流上傳:

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

以檔案物件上傳:

File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try { params.put("profile_picture", myFile); } catch (FileNotFoundException e) {}

以位元組陣列上傳:

byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

六、下載二進制檔案

使用 FileAsyncHttpResponseHandler 即可下載圖片等二進制檔案:

AsyncHttpClient client = new AsyncHttpClient();
client.get("www.my.com/movies.jpg", new FileAsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, File response) {
        // 取得檔案
    }
});

若要發送 JSON 等其他類型請求,只要替換成 new JsonHttpResponseHandler(){ ... } 即可。

七、HTTP 身份驗證

AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username", "password/token");
client.get("https://www.my.com");
// 也可指定更精確的驗證範圍
client.setBasicAuth("username", "password", new AuthScope("www.my.com", 80, AuthScope.ANY_REALM));
client.get("https://www.my.com");

總結


Android 網絡框架的學習到此告一段落,我們走過了 Volley、Picasso 與 android-async-http。使用時請依需求與各框架特性做選擇,初期掌握基本用法即可,之後再深入研究源碼,才能在開發中得心應手。

綜合這幾篇文章,引入第三方框架大致離不開這幾步:

  1. 依需求到 GitHub 等網站尋找合適且流行的框架
  2. 熟悉框架的特性、使用場景與缺陷
  3. 將 jar 包引入專案
  4. 依官方範例掌握基本用法
  5. 多做練習,熟悉使用場景
  6. 研究源碼,必要時改寫以適應自身需求
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved