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
android-async-http最簡單基礎的使用只需以下步驟: 併發
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,官方示例代碼以下:
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 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);
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(); }
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()); } } });
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類用於實現Apache HttpClient的CookieStore接口, 可自動將cookie保存到Android設備的SharedPreferences中, 若是你打算使用cookie來管理驗證會話,這個很是有用,由於用戶能夠保持登陸狀態,無論關閉仍是從新打開你的app。
文檔裏介紹了持久化Cookie的步驟:
下面這個例子就是鐵證:
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:例子用的在牛逼還不如閱讀開頭列出的官方文檔和源碼吧。