編輯:關於 Android 程式設計
這是 Android 網絡框架系列的最後一篇。前面我們聊過 Volley 與 Picasso,這次把第三方庫 android-async-http 收進口袋,並在結尾處整理如何在開發中選用與駕馭第三方框架。
android-async-http 是對 HttpClient 的頂層封裝,所有 Request 都運行在獨立於 UI 線程的其他線程中,而回調的處理方式又與 Handler 發送 message 的邏輯一致,你也可以讓它跑在 Service 或背景線程裡。
主要特點:
與所有第三方庫一樣,先將 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(){ ... });
透過 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);
使用 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(){ ... } 即可。
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。使用時請依需求與各框架特性做選擇,初期掌握基本用法即可,之後再深入研究源碼,才能在開發中得心應手。
綜合這幾篇文章,引入第三方框架大致離不開這幾步:
Android 多解析度適配的實戰經驗分享
在開發 Android 專案時,多解析度適配一直是個令人頭痛的老問題。由於裝置碎片化嚴重,同一套介面往往要在各種尺寸的手機上都呈現良好效果。本文分享我在實際專案中走過的彎
Bitmap 加載優化:使用 inSampleSize 降低記憶體
在 Android 中,圖片是記憶體消耗的主要來源之一。BitmapFactory 提供多種解碼方式,可從檔案、資源、串流或位元組陣列載入圖片。若直接載入原圖,容易造成
深入解析 Android ViewStub:延遲加載的適用邊界與實踐要點
開發中經常遇到這種情形:某些 View 或某塊布局要不要顯示,得等運行時才能定。最直覺的寫法是把所有候選 View 都寫進布局,初始設為 View.GONE,再在代碼裡按
Android 單元測試入門:兩種測試工程的建立方式
在 Android 中撰寫測試,基本上可以分成兩種做法: 一、在同一個工程內直接撰寫測試程式碼。 二、另外建立一個專用的測試工程。 一、在同一個工程內撰寫測試 步驟如下: