android-async-http框架庫使用基礎

開源項目連接

android-async-http倉庫:git clone https://github.com/loopj/android-async-http html

android-async-http主頁:http://loopj.com/android-async-http/ java


背景知識

開始使用分析前仍是先了解下Android的HTTP一些過往趣事: android

關於Android HTTP推薦的Google官方連接 git

HttpClient擁有衆多的API,實現穩定,bug不多。 HttpURLConnection是一種多用途、輕量的HTTP客戶端,使用它來進行HTTP操做能夠適用於大多數的應用程序。 HttpURLConnection的API比較簡單、擴展容易。不過在Android 2.2版本以前,HttpURLConnection一直存在着一些bug。 好比說對一個可讀的InputStream調用close()方法時,就有可能會致使鏈接池失效了。 因此說2.2以前推薦使用HttpClient,2.2以後推薦HttpURLConnection。 github

好了,那如今話又說回來,在android-async-http中使用的是HttpClient。哎…好像在Volley中分析過Volley對不一樣版本進行了判斷, 因此針對不一樣版本分別使用了HttpClient和HttpURLConnection。仍是google牛逼啊! json

回過神繼續android-async-http吧,不瞎扯了。 api

android-async-http是專門針對Android在Apache的HttpClient基礎上構建的異步http鏈接。全部的請求全在UI(主)線程以外執行, 而callback使用了Android的Handler發送消息機制在建立它的線程中執行。 服務器

相似Volley同樣,使用一個優秀框架以前就是必須得先知道他的特性,以下就是android-async-http的特性: cookie

  1. 發送異步http請求,在匿名callback對象中處理response信息;
  2. http請求發生在UI(主)線程以外的異步線程中;
  3. 內部採用線程池來處理併發請求;
  4. 經過RequestParams類構造GET/POST;
  5. 內置多部分文件上傳,不須要第三方庫支持;
  6. 流式Json上傳,不須要額外的庫;
  7. 能處理環行和相對重定向;
  8. 和你的app大小相比來講,庫的size很小,全部的一切只有90kb;
  9. 在各類各樣的移動鏈接環境中具有自動智能請求重試機制;
  10. 自動的gzip響應解碼;
  11. 內置多種形式的響應解析,有原生的字節流,string,json對象,甚至能夠將response寫到文件中;
  12. 永久的cookie保存,內部實現用的是Android的SharedPreferences;
  13. 經過BaseJsonHttpResponseHandler和各類json庫集成;
  14. 支持SAX解析器;
  15. 支持各類語言和content編碼,不只僅是UTF-8;

總體操做流程

android-async-http最簡單基礎的使用只需以下步驟: 併發

  1. 建立一個AsyncHttpClient;
  2. (可選的)經過RequestParams對象設置請求參數;
  3. 調用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 TwitterRestClient { private static final String BASE_URL = "http://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; } }

經過官方這個推薦例子能夠發現,咱們在用時能夠直接經過類名調用須要的請求方法。因此咱們能夠本身多封裝一些不一樣的請求方法,好比參數不一樣的方法,下載方法, 上傳方法等。


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的步驟:

  1. 建立 AsyncHttpClient實例對象;
  2. 將客戶端的cookie保存到PersistentCookieStore實例對象,帶有activity或者應用程序context的構造方法;
  3. 任何從服務器端獲取的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:例子用的在牛逼還不如閱讀開頭列出的官方文檔和源碼吧。

相關文章
相關標籤/搜索