Github 上Top1的Android 非同步網路請求架構

來源:互聯網
上載者:User

標籤:android   網路   請求   非同步   github   

今天給大家分享一個github上Top1的Android非同步網路請求架構的使用方法,我給大家分享一個它的基本用法。

先來一個簡單的get請求

AsyncHttpClient client = new 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    }});

這樣用我們每次都要new 非常的麻煩,我們可以簡單的封裝一下,直接調用靜態方法,並且對網域名稱做統一添加,自動轉換為最終的url請求地址

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;  }}

然後這樣使用,請求返回一個Json類型的傳回值

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);       }   });

添加GET / POST參數 RequestParams

//建立空 RequestParams 並立即添加一些參數:RequestParams params = new RequestParams();params.put("key", "value");params.put("more", "data");//建立 RequestParams 一個參數:RequestParams params = new RequestParams("single", "value");//建立 RequestParams 從現有的 地圖 鍵/值的字串:HashMap<String, String> paramMap = new HashMap<String, String>();paramMap.put("key", "value");RequestParams params = new RequestParams(paramMap);

上傳檔案 RequestParams

//添加一個 InputStream 到 RequestParams 上傳:InputStream myInputStream = blah;RequestParams params = new RequestParams();params.put("secret_passwords", myInputStream, "passwords.txt");//添加一個 檔案 對象的 RequestParams 上傳:File myFile = new File("/path/to/file.png");RequestParams params = new RequestParams();try {    params.put("profile_picture", myFile);} catch(FileNotFoundException e) {}//添加一個位元組數組 RequestParams 上傳:byte[] myByteArray = blah;RequestParams params = new RequestParams();params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

下載資料資料, FileAsyncHttpResponseHandler

#FileAsyncHttpResponseHandler 類可以被用來擷取位元據 照片和其他檔案。 例如:
AsyncHttpClient client = new AsyncHttpClient();client.get("http://example.com/file.png", new FileAsyncHttpResponseHandler(/* Context */ this) {    @Override    public void onSuccess(int statusCode, Header[] headers, File response) {        // Do something with the file `response`    }});

添加HTTP基本驗證憑據

//一些請求可能需要使用者名稱/密碼憑據在處理API使用HTTP基本驗證請求訪問的服務。 您可以使用這個方法 setBasicAuth() 提供您的憑據。//設定使用者名稱/密碼對任何主機和領域特定的請求。 預設情況下,任何主機的認證範圍,港口和領域。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");

持久化Cookie儲存與 PersistentCookieStore

//這個庫還包含一個 PersistentCookieStore 這是一個實現 Apache HttpClient CookieStore 介面,自動儲存 餅乾, SharedPreferences 儲存在Android裝置上。//這是非常有用的,如果你想使用cookie來管理身分識別驗證 會話,因為使用者將繼續登入即使關閉 重啟應用程式。//首先,建立的執行個體 AsyncHttpClient :AsyncHttpClient myClient = new AsyncHttpClient();//現在將這個客戶的cookie儲存的一個新執行個體 PersistentCookieStore ,由一個活動或應用程式上下文 (通常是 這 就足夠了):PersistentCookieStore myCookieStore = new PersistentCookieStore(this);myClient.setCookieStore(myCookieStore);//任何Cookie收到伺服器將會儲存在持久化CookieStore。//添加自己的CookieStore ,只需構建一個新的Cookie和 調用 addCookie :BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");newCookie.setVersion(1);newCookie.setDomain("mydomain.com");newCookie.setPath("/");myCookieStore.addCookie(newCookie);

下載 | 點擊這裡

github地址 | 點擊這裡

/** * -------------- * 歡迎轉載   |  轉載請註明 * -------------- * @author zsl * @github https://github.com/yy1300326388 * @blog http://blog.csdn.net/yy1300326388 */

Github 上Top1的Android 非同步網路請求架構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.