Android Asynchronous Http Client--Android 開源的網路非同步載入類

來源:互聯網
上載者:User

標籤:android   style   class   blog   code   java   

整理Android Asynchronous Http Client的使用

Android Asynchronous Http Client(AHC)一個回調式的Android網路請求庫概括:AHC是基於Apache的HttpClient 庫,所有的網路請求過程在UI線程之外進行,而回調是在Handler裡面處理。也可以再Service或者背景程式裡面使用,這個庫會自動識別並在相應的Context進行處理。
特點:
  1. 非同步發送HTTP請求,在回呼函數中處理響應
  2. HTTP請求過程不在UI線程進行
  3. 使用線程池來管理並發數
  4. 支援GET/POST請求參數單獨設定
  5. 無需其他庫上傳序列化JSON資料
  6. 處理重新導向
  7. 體積小,只有90K
  8. 針對不同的網路連接對重試次數進行智能最佳化
  9. 支援gzip
  10. 二進位通訊協定使用BinaryHttpResponseHandler處理
  11. 內建Json解析,使用JsonHttpResponseHandler對響應進行處理
  12. 使用FileAsyncHttpResponseHandler直接將響應儲存到檔案中
  13. 動態儲存Cookie,將Cookie儲存到應用的SharedPreferences中
  14. 使用BaseJsonHttpResponseHandler可以搭配Jackson JSON,Gson或者其他的Json還原序列化庫
  15. 支援SAX解析,使用SaxAsyncHttpResponseHandler
  16. 支援多語言多種編碼方式,不只是UTF-8
誰在用Instagram,Pinterest,Pose。。。。怎麼用MVN:
<dependency>    <groupId>com.loopj.android</groupId>    <artifactId>android-async-http</artifactId>    <version>1.4.5</version></dependency>
導包:
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<String, String> paramMap = new HashMap<String, String>();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-httpMVN地址:http://central.maven.org/maven2/com/loopj/android/android-async-http/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.