Android Asynchronous Http Client(AHC)一個回調式的Android網路請求庫概括:AHC是基於Apache的HttpClient 庫,所有的網路請求過程在UI線程之外進行,而回調是在Handler裡面處理。也可以再Service或者背景程式裡面使用,這個庫會自動識別並在相應的Context進行處理。
特點:非同步發送HTTP請求,在回呼函數中處理響應HTTP請求過程不在UI線程進行使用線程池來管理並發數支援GET/POST請求參數單獨設定無需其他庫上傳序列化JSON資料處理重新導向體積小,只有90K針對不同的網路連接對重試次數進行智能最佳化支援gzip二進位通訊協定使用BinaryHttpResponseHandler處理
內建Json解析,使用JsonHttpResponseHandler對響應進行處理使用FileAsyncHttpResponseHandler直接將響應儲存到檔案中動態儲存Cookie,將Cookie儲存到應用的SharedPreferences中使用BaseJsonHttpResponseHandler可以搭配Jackson JSON,Gson或者其他的Json還原序列化庫支援SAX解析,使用SaxAsyncHttpResponseHandler支援多語言多種編碼方式,不只是UTF-8誰在用Instagram,Pinterest,Pose。。。。怎麼用MVN:
com.loopj.android android-async-http 1.4.5
導包:
import com.loopj.android.http.*;
建立一個AsyncHttpClient 對象並發送一個請求:
client.get(http://www.google.com, new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { // called when response HTTP status is 200 OK } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { // called when response HTTP status is 4XX (eg. 401, 403, 404) } @Override public void onRetry(int retryNo) { // called when request is retried}});
推薦用法:定義一個靜態Http Client建立一個網路工具類,定義一個全域靜態Http Client。
import com.loopj.android.http.*;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; }}
就很容易的在需要請求網路的地方發送 網路請求:
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) { // If the response is JSONObject instead of expected JSONArray } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) { // Pull out the first event on the public timeline JSONObject firstEvent = timeline.get(0); String tweetText = firstEvent.getString(text); // Do something with the response System.out.println(tweetText); } }); }}
API文檔http://loopj.com/android-async-http/doc/com/loopj/android/http/AsyncHttpClient.html
使用PersistentCookieStore儲存Cookie這個庫包含一個
PersistentCookieStore ,這個類是Apache HttpClient CookieStore 介面的實現,它可以自動將cookies儲存到SharedPreferences 。 如果你需要使用cookie保持認證會話,這將是特別重要的,因為即使使用者關掉了應用仍然可以登入狀態。 首先,建立一個AsyncHttpClient對象:
AsyncHttpClient myClient = new AsyncHttpClient();
現在將client的Cookie儲存到一個PersistentCookieStore,構造方法需要有一個上下文(Activity,Application都可以,通常this就OK了)。
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);myClient.setCookieStore(myCookieStore);
所有從server擷取到的資料都持續的儲存。 如果想自己設定cookie,只需要建立一個新的cookie,並調用addCookie:
BasicClientCookie newCookie = new BasicClientCookie(cookiesare, awesome);newCookie.setVersion(1);newCookie.setDomain(mydomain.com);newCookie.setPath(/);myCookieStore.addCookie(newCookie);
詳情請看 PersistentCookieStore Javadoc
使用RequestParams來添加GET/POST請求參數類RequestParams 用來為請求添加請求參數,RequestParams 可以有好幾種方法進行建立和設定。 1.建立一個空的RequestParams 然後添加參數:
RequestParams params = new RequestParams();params.put(key, value);params.put(more, data);
2.建立一個帶有一對參數的RequestParams
RequestParams params = new RequestParams(single, value);
3.建立一個帶有Map的RequestParams
HashMap paramMap = new HashMap();paramMap.put(key, value);RequestParams params = new RequestParams(paramMap);
詳情請參考:RequestParams Javadoc
使用RequestParams上傳檔案RequestParams 可以支援多媒體檔案上傳,可以通過以下方式實現: 1.將一個Inputstream添加到將要上傳的RequestParams
InputStream myInputStream = blah;RequestParams params = new RequestParams();params.put(secret_passwords, myInputStream, passwords.txt);
2.File方式
File myFile = new File(/path/to/file.png);RequestParams params = new RequestParams();try { params.put(profile_picture, myFile);} catch(FileNotFoundException e) {}3.byte數組形式
byte[] myByteArray = blah;RequestParams params = new RequestParams();params.put(soundtrack, new ByteArrayInputStream(myByteArray), she-wolf.mp3);
詳情:RequestParams Javadoc
使用FileAsyncHttpResponseHandler下載二進位檔案類FileAsyncHttpResponseHandler 可以用來擷取二進位檔案,片,語音等檔案:
AsyncHttpClient client = new AsyncHttpClient();client.get(http://example.com/file.png, new FileAsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, File response) { // Do something with the file `response` }});
詳情: FileAsyncHttpResponseHandler Javadoc
添加基本的認證憑證一些請求可能需要類似username/password 的憑證
AsyncHttpClient client = new AsyncHttpClient();client.setBasicAuth(username,password/token);client.get(http://example.com);
當然你也可以定製
AsyncHttpClient client = new AsyncHttpClient();client.setBasicAuth(username,password, new AuthScope(example.com, 80, AuthScope.ANY_REALM));client.get(http://example.com);
詳情:RequestParams Javadoc
說明文檔:http://loopj.com/android-async-http/ GITHUB地址:https://github.com/loopj/android-async-http MVN地址:http://central.maven.org/maven2/com/loopj/android/android-async-http/