Android之Async-http

來源:互聯網
上載者:User

標籤:android   async-http   

簡介:

Async-http是一款國外的開源架構,作者是loopj。是基於Apache HttpClient庫的。可以方便快速高效的進行網路資料請求和發送,檔案下載和上傳。


特點:

清晰的網路請求回調
請求使用ThreadPool,限制並發資源使用方式
GET / POST基於參數構建使用(RequestParams),方便
Multipart 檔案上傳,大資料上傳下載
自動智能請求重試,最佳化了品質不一的移動串連

內建響應解析成JSON,使用JsonHttpResponseHandler

持久化cookie儲存,儲存cookie到你的應用程式的SharedPreferences
二進位檔案(圖片等)的下載,使用BinaryHttpResponseHandler


用法:

建立請求首先建立請求用戶端對象。
然後進行相應的Get和Post請求,請求結果在回調裡擷取解析。
Async-http的Get和Post請求可以基於參數化請求(RequestParams),可以清晰方便的將你的請求參數放到裡面,然後進行Get和Post請求。


樣本:

首先我們需要選擇一個網路服務API,這裡我選擇彙總資料裡面的手機歸屬地查詢API,1註冊2申請,申請之後會為你的應用程式指派一個AppKey,下面是API說明:

/***介面地址:http://apis.juhe.cn/mobile/get支援格式:JSON/XML請求方式:GET/POST請求樣本:http://apis.juhe.cn/mobile/get?phone=13429667914&key=您申請的KEY請求參數: 名稱類型必填說明 phoneint是需要查詢的手機號碼或手機號碼前7位 keystring是應用APPKEY(應用詳細頁查詢) dtypestring否返回資料的格式,xml或json,預設json調用範例及調試工具:  API測試載入器 返回欄位: 名稱類型說明 error_codeint返回碼 reasonstring返回說明 resultstring返回結果集 provincestring省份 citystring城市 areacodestring區號 zipstring郵編 companystring電訊廠商 cardstring卡類型**/
在使用Async-Http之前,必須將jar包放入工程中去,我這裡寫了一個範例程式碼,如下:

public class MainActivity extends Activity implements OnClickListener{// Get請求方式的URLprivate static final String URL_GET = "http://apis.juhe.cn/mobile/get?phone=18952201314&key=a53155cc6af64daabc66655b060db56a";// Post請求方式的URLprivate static final String URL_POST = "http://apis.juhe.cn/mobile/get?";//聲明一個AsyncHttpClient的變數 private AsyncHttpClient asyncHttpClient = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);setupViews();initAsyncHttp();}@Overridepublic void onClick(View v) {int id = v.getId();switch (id) {case R.id.button1://用Get方式提交請求asyncHttpGet();break;case R.id.button2://用Get方式提交請求asyncHttpPost();break;default:break;}}private void setupViews(){findViewById(R.id.button1).setOnClickListener(this);findViewById(R.id.button2).setOnClickListener(this);}//初始化asyncHttpprivate void initAsyncHttp(){asyncHttpClient = new AsyncHttpClient();}private void asyncHttpGet(){//當Get請求被發送時,onStart、onSuccess或onFailure、onFinish方法將依次被回調asyncHttpClient.get(URL_GET, new AsyncHttpResponseHandler(){@Overridepublic void onStart() {System.out.println("get request onStart...");super.onStart();}@Overridepublic void onSuccess(String arg0) {String result = arg0;//如果需要將result通過Json解析封裝為對象,可參考《Android之Volley》中的代碼System.out.println(result);super.onSuccess(arg0);}@Overridepublic void onFailure(Throwable arg0) {System.out.println("get request onFailure...");super.onFailure(arg0);}@Overridepublic void onFinish() {System.out.println("get request onFinish...");super.onFinish();}});}private void asyncHttpPost(){//建立一個RequestParams對象用來儲存Post請求的參數RequestParams requestParams = new RequestParams();//佈建要求參數requestParams.put("phone", "18952201314");requestParams.put("key", "a53155cc6af64daabc66655b060db56a");//當Post請求被發送時,onStart、onSuccess或onFailure、onFinish方法將依次被回調//因為返回的資料是json格式的,所以這裡的Handler可以選擇成JsonHttpResponseHandlerasyncHttpClient.post(URL_POST, requestParams, new JsonHttpResponseHandler(){@Overridepublic void onStart() {System.out.println("post request onStart...");super.onStart();}@Overridepublic void onSuccess(JSONObject arg0) {// 這裡回調參數直接是JSONObject類型,省去了我們一道程式System.out.println(arg0.toString());super.onSuccess(arg0);}@Overridepublic void onFailure(Throwable arg0) {System.out.println("post request onFailure...");super.onFailure(arg0);}@Overridepublic void onFinish() {System.out.println("post request onFinish...");super.onFinish();}});}}


整個工程的代碼壓縮包如下,需要的可以下載:

Android Async-Http Demo

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.