开源框架AsyncHttpClient使用

分类: Android平台

在大神岩岩的推荐下使用了AsyncHttpClient框架,用过之后感觉还是灰常好用滴。
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

posted @ 2014-08-12 17:23  新感觉  阅读(310)  评论(0编辑  收藏  举报