編輯:關於 Android 程式設計
在 Android 上做網絡請求,早期幾乎繞不開 Apache HttpClient。Android Asynchronous Http Client(簡稱 Async HTTP)就是在它之上封裝出來的一層,目標只有一個:讓異步請求寫起來像同步一樣輕鬆。
核心思路是所有請求都在主線程之外發出,而回調邏輯通過 Android 的 Handler 消息機制,回到創建回調時的那個線程上執行——也就是說,你在 onSuccess() 裡可以直接更新 UI,不用自己折騰 runOnUiThread。
功能清單頗為實用:
RequestParams 統一構造 GET/POST 參數。BinaryHttpResponseHandler 下載二進制數據(圖片等)。JsonHttpResponseHandler 直接把響應解析成 JSON。值得一提的是,Instagram、Pinterest、Heyzap 等頭部應用都曾把它用在生產環境裡。
從 GitHub 下載最新 jar 丟進工程的 libs/,導入包:
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);
}
});
實戰中更推薦把 client 收斂到一個類裡,讓業務代碼遠離細節。以 Twitter 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;
}
}
之後業務層調用起來就非常乾淨:
class TwitterRestClientUsage {
public void getPublicTimeline() throws JSONException {
TwitterRestClient.get("statuses/public_timeline.json", null,
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray timeline) {
JSONObject firstEvent = timeline.get(0);
String tweetText = firstEvent.getString("text");
System.out.println(tweetText);
}
});
}
}
庫裡自帶 PersistentCookieStore,實現了 Apache 的 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 支持多種構造方式:
// 空對象後逐個添加
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);
上傳文件時,InputStream、File、字節數組三種形式都支持:
// InputStream
InputStream myInputStream = blah;
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[] myByteArray = blah;
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
圖片、音頻之類的非文本內容用 BinaryHttpResponseHandler,可以順手限制允許的 Content-Type:
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) {
// 處理文件字節
}
});
有些接口需要賬號密碼,用 setBasicAuth() 提供憑證即可。默認作用域是任意 host、port 和 realm:
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username", "password/token");
client.get("https://example.com");
更推薦指定精確的認證作用域:
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username", "password",
new AuthScope("example.com", 80, AuthScope.ANY_REALM));
client.get("https://example.com");
克隆倉庫後,把 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;Marek Sebera 自 1.4.4 版本起接手維護,Micah Fivecoate 則是 RequestParams 的主要貢獻者。此外還受益於 Droid Fu 項目的重試策略、Rafael Sanches 的 SimpleMultipartEntity 原始代碼等社區成果。
Android HttpClient 使用詳解:GET、POST、檔案上傳與連線管理
Android 除了使用 java.net 相關 API,也可以透過 Apache HttpClient 完成 HTTP 請求。HttpClient 對 HTTP 協定支
如何在 XML 中定義 Android 選單
除了用程式碼建立選單,Android 也支援在 XML 中定義選單。這種做法能把介面結構與程式邏輯分離,讓程式碼更清楚,也方便日後維護。建立選單資源首先,在 res 目錄
用 ImageView 搭配 AnimationDrawable 打造 ProgressBar 旋轉效果
ProgressBar 大家都不陌生,XML 裡一引用、加幾個屬性就能跑。但每個 App 都有自己的視覺調性,直接用系統預設那張轉圈圖,總覺得和整體風格不搭。 自定義 P
Android 資源文件中的 XML 全景圖:各目錄職責與用法示例
XML 作為一種可擴展標記語言,天生適合承載結構化數據,因此在 Android 項目裡可謂隨處可見:根目錄下必不可少的 AndroidManifest.xml 清單文件,