非同步網路載入開源架構AsyncHttpClient使用

來源:互聯網
上載者:User

標籤:http   使用   os   io   資料   art   ar   代碼   


AsyncHttpClient是非同步,但是有時候我們需要得到請求的結果集來返回給某個函數,由於是非同步,所以不能夠直接return會去,所以可以定義一個interface來給調用AsyncHttpClient方法的一個回調來擷取結果集,代碼如下:
定義回調介面:

點擊(此處)摺疊或開啟

  1. private static Callback mCallback;
  2.     
  3.     public interface Callback{
  4.         abstract void rankingsResultData(JSONArray result,int code);
  5.         abstract void postResultData(int result);
  6.         abstract void shareResultData(int result);
  7.     }

調用非同步架構代碼:

點擊(此處)摺疊或開啟

  1. public static void getRankingList(int integType,int sortType,int size) {
  2.         mClient.post(GET_RANKINGList, getRankingsParms(integType,sortType,size), new JsonHttpResponseHandler(){
  3.             @Override
  4.             public void onSuccess(JSONObject response) {
  5.                 if (response != null) {
  6.                     try {
  7.                         JSONObject status = response.getJSONObject("state");
  8.                         int code = status.getInt("code");
  9.                         JSONArray list = null;
  10.                         if (code == 0) {
  11.                             list = response.getJSONArray("items");
  12.                         } 
  13.                         if(mCallback != null){
  14.                             mCallback.rankingsResultData(list,code);
  15.                         }
  16.                     } catch (JSONException e) {
  17.                         e.printStackTrace();
  18.                         if(mCallback != null){
  19.                             mCallback.rankingsResultData(null,2);
  20.                         }
  21.                     }
  22.                 }
  23.             }
  24.             public void onFailure(Throwable e, JSONObject errorResponse) {
  25.                 if(mCallback != null){
  26.                     mCallback.rankingsResultData(null,-1);
  27.                 }
  28.             }
  29.             public void onFailure(Throwable error, String content) {
  30.                 if(mCallback != null){
  31.                     mCallback.rankingsResultData(null,-1);
  32.                 }
  33.             }            
  34.         });        
  35.     }

當調用getRankingList 非同步請求完成的時候會回調rankingsResultData來得到返回的資料或者能得到請求是否chengg

聯繫我們

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