android-async-http框架庫使用基礎
開源項目鏈接
android-async-http倉庫:git clone https://github.com/loopj/android-async-http
android-async-http主頁:http://loopj.com/android-async-http/
背景知識
開始使用分析前還是先了解下Android的HTTP一些過往趣事:
HttpClient擁有眾多的API,實現穩定,bug很少。
HttpURLConnection是一種多用途、輕量的HTTP客戶端,使用它來進行HTTP操作可以適用于大多數的應用程序。HttpURLConnection的API比較簡單、擴展容易。不過在Android 2.2版本之前,HttpURLConnection一直存在著一些bug。
比如說對一個可讀的InputStream調用close()方法時,就有可能會導致連接池失效了。所以說2.2之前推薦使用HttpClient,2.2之后推薦HttpURLConnection。
好了,那現在話又說回來,在android-async-http中使用的是HttpClient。哎…好像在Volley中分析過Volley對不同版本進行了判斷,所以針對不同版本分別使用了HttpClient和HttpURLConnection。還是google牛逼啊!
回過神繼續android-async-http吧,不瞎扯了。android-async-http是專門針對Android在Apache的HttpClient基礎上構建的異步http連接。所有的請求全在UI(主)線程之外執行,而callback使用了Android的Handler發送消息機制在創建它的線程中執行。
類似Volley一樣,使用一個優秀框架之前就是必須得先知道他的特性,如下就是android-async-http的特性:
-
發送異步http請求,在匿名callback對象中處理response信息;
-
http請求發生在UI(主)線程之外的異步線程中;
-
內部采用線程池來處理并發請求;
-
通過RequestParams類構造GET/POST;
-
內置多部分文件上傳,不需要第三方庫支持;
-
流式Json上傳,不需要額外的庫;
-
能處理環行和相對重定向;
-
和你的app大小相比來說,庫的size很小,所有的一切只有90kb;
-
在各種各樣的移動連接環境中具備自動智能請求重試機制;
-
自動的gzip響應解碼;
-
內置多種形式的響應解析,有原生的字節流,string,json對象,甚至可以將response寫到文件中;
-
永久的cookie保存,內部實現用的是Android的SharedPreferences;
-
通過BaseJsonHttpResponseHandler和各種json庫集成;
-
支持SAX解析器;
-
支持各種語言和content編碼,不僅僅是UTF-8;
整體操作流程
android-async-http最簡單基礎的使用只需如下步驟:
-
創建一個AsyncHttpClient;
-
(可選的)通過RequestParams對象設置請求參數;
-
調用AsyncHttpClient的某個get方法,傳遞你需要的(成功和失敗時)callback接口實現,一般都是匿名內部類,實現了AsyncHttpResponseHandler,類庫自己也提供許多現成的response handler,你一般不需要自己創建。
AsyncHttpClient與AsyncHttpResponseHandler基礎GET體驗
AsyncHttpClient類通常用在android應用程序中創建異步GET, POST, PUT和DELETE HTTP請求,請求參數通過RequestParams實例創建,響應通過重寫匿名內部類ResponseHandlerInterface方法處理。
如下代碼展示了使用AsyncHttpClient與AsyncHttpResponseHandler的基礎操作:
AsyncHttpClient client = new AsyncHttpClient();
client.get("www.baidu.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onFinish() {
super.onFinish();
}
@Override
public void onRetry(int retryNo) {
super.onRetry(retryNo);
}
@Override
public void onCancel() {
super.onCancel();
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
super.onProgress(bytesWritten, totalSize);
}
}); 官方推薦AsyncHttpClient靜態實例化的封裝
注意:官方推薦使用一個靜態的AsyncHttpClient,官方示例代碼如下:
public class 推terRestClient {
private static final String BASE_URL = "http://api.推ter.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;
}
} 通過官方這個推薦例子可以發現,我們在用時可以直接通過類名調用需要的請求方法。所以我們可以自己多封裝一些不同的請求方法,比如參數不同的方法,下載方法,上傳方法等。
RequestParams的基礎使用
RequestParams params = new RequestParams();
params.put("username", "yanbober");
params.put("password", "123456");
params.put("email", "yanbobersky@email.com");
/* * Upload a File */
params.put("file_pic", new File("test.jpg"));
params.put("file_inputStream", inputStream);
params.put("file_bytes", new ByteArrayInputStream(bytes));
/* * url params: "user[first_name]=jesse&user[last_name]=yan" */
Map<String, String> map = new HashMap<String, String>();
map.put("first_name", "jesse");
map.put("last_name", "yan");
params.put("user", map);
/* * url params: "what=haha&like=wowo" */
Set<String> set = new HashSet<String>();
set.add("haha");
set.add("wowo");
params.put("what", set);
/* * url params: "languages[]=Java&languages[]=C" */
List<String> list = new ArrayList<String>();
list.add("Java");
list.add("C");
params.put("languages", list);
/* * url params: "colors[]=blue&colors[]=yellow" */
String[] colors = { "blue", "yellow" };
params.put("colors", colors);
/* * url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female" */
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> user1 = new HashMap<String, String>();
user1.put("age", "30");
user1.put("gender", "male");
Map<String, String> user2 = new HashMap<String, String>();
user2.put("age", "25");
user2.put("gender", "female");
listOfMaps.add(user1);
listOfMaps.add(user2);
params.put("users", listOfMaps);
/* * 使用實例 */
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://localhost:8080/androidtest/", params, responseHandler); JsonHttpResponseHandler帶Json參數的POST
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "ryantang");
StringEntity stringEntity = new StringEntity(jsonObject.toString());
client.post(mContext, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler(){
@Override
public void onSuccess(JSONObject jsonObject) {
super.onSuccess(jsonObject);
}
});
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} BinaryHttpResponseHandler下載文件
client.get("http://download/file/test.java", new BinaryHttpResponseHandler() {
@Override
public void onSuccess(byte[] arg0) {
super.onSuccess(arg0);
File file = Environment.getExternalStorageDirectory();
File file2 = new File(file, "down");
file2.mkdir();
file2 = new File(file2, "down_file.jpg");
try {
FileOutputStream oStream = new FileOutputStream(file2);
oStream.write(arg0);
oStream.flush();
oStream.close();
} catch (Exception e) {
e.printStackTrace();
Log.i(null, e.toString());
}
}
}); RequestParams上傳文件
File myFile = new File("/sdcard/test.java");
RequestParams params = new RequestParams();
try {
params.put("filename", myFile);
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://update/server/location/", params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, String content) {
super.onSuccess(statusCode, content);
}
});
} catch(FileNotFoundException e) {
e.printStackTrace();
} PersistentCookieStore持久化存儲cookie
官方文檔里說PersistentCookieStore類用于實現Apache HttpClient的CookieStore接口,可自動將cookie保存到Android設備的SharedPreferences中,如果你打算使用cookie來管理驗證會話,這個非常有用,因為用戶可以保持登錄狀態,不管關閉還是重新打開你的app。
文檔里介紹了持久化Cookie的步驟:
-
創建 AsyncHttpClient實例對象;
-
將客戶端的cookie保存到PersistentCookieStore實例對象,帶有activity或者應用程序context的構造方法;
-
任何從服務器端獲取的cookie都會持久化存儲到myCookieStore中,添加一個cookie到存儲中,只需要構造一個新的cookie對象,并且調用addCookie方法;
下面這個例子就是鐵證:
AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore cookieStore = new PersistentCookieStore(this);
client.setCookieStore(cookieStore);
BasicClientCookie newCookie = new BasicClientCookie("name", "value");
newCookie.setVersion(1);
newCookie.setDomain("mycompany.com");
newCookie.setPath("/");
cookieStore.addCookie(newCookie); 總結性的嘮叨幾句
AsyncHttpResponseHandler是一個請求返回處理、成功、失敗、開始、完成等自定義的消息的類,如上第一個基礎例子中所示。
BinaryHttpResponseHandler是繼承AsyncHttpResponseHandler的子類,這是一個字節流返回處理的類,用于處理圖片等類。
JsonHttpResponseHandler是繼承AsyncHttpResponseHandler的子類,這是一個json請求返回處理服務器與客戶端用json交流時使用的類。
AsyncHttpRequest繼承自Runnable,是基于線程的子類,用于異步請求類, 通過AsyncHttpResponseHandler回調。
PersistentCookieStore繼承自CookieStore,是一個基于CookieStore的子類, 使用HttpClient處理數據,并且使用cookie持久性存儲接口。
PS:例子用的在牛逼還不如閱讀開頭列出的官方文檔和源碼吧。