編輯:關於 Android 程式設計
AHC 建立在 Apache 的 HttpClient 之上,把整個網路請求過程移出 UI 執行緒,回呼則透過 Handler 派送回主執行緒。它也可以在 Service 或背景程式中使用,會自動辨識並在對應的 Context 上處理回呼。
JsonHttpResponseHandler 解析 JSON;FileAsyncHttpResponseHandler 直接把回應存成檔案;BinaryHttpResponseHandler 處理二進位協議BaseJsonHttpResponseHandler 可搭配 Jackson、Gson 等反序列化庫SaxAsyncHttpResponseHandler)使用者名單裡有 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) {
// 請求被重試時呼叫
}
});
實務上不要到處 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,是 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);
// 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,它們在攔截器、連線池與非同步模型上都更成熟。
手把手做一個安卓聊天機器人:接入圖靈機器人 API
智能聊天機器人是不少入門練習的首選項目:界面結構清晰、邏輯不複雜,又能把網絡請求、線程通信、列表適配器這幾塊知識串起來。這裡借圖靈機器人的開放接口做一個仿微信風格的聊天界
打造萬能下拉/上拉刷新框架 XRefreshView(二)
一、前言 上一篇發表之後忙了大半個月,但每天晚上下班後仍持續更新與維護 XRefreshView,也依據一些朋友的回饋修掉了若干問題。這次再寫一篇,是因為它已經走到了功能
Android 自訂 ProgressBar 樣式(背景色與一級、二級進度條顏色)
本文將透過實例,說明如何以程式實作自訂的 ProgressBar 樣式,涵蓋背景色、一級進度條與二級進度條的顏色設定,分享給大家參考。 效果圖如下,本例中同時設定了一級進
Tinker 熱更新完整指南:集成、補丁生成與加載流程
Tinker 的效果與限制 Tinker 是常見的 Android 熱更新方案,可在不重新發佈完整安裝包的情況下,推送補丁修正部分問題。不過,Tinker 也有已知限制,