码迷,mamicode.com
首页 > 移动开发 > 详细

Android封装数据请求AsyncHttpClient 和 Volley

时间:2015-06-16 20:43:22      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

将 AsyncHttpClient 和 Volley 的jar导入的libs目录下面,

导入遇见的问题,导入后到时没有对应的类,,解决方法,在你导入的包下面右击点击add to Library。。就可以了。是不是很菜啊。我菜我快乐。。

技术分享

1 NetRequest 封装的数据请求,,跟加载图片  

2 NetUtil 配置请求数据。。

3 macro 存放的是宏。。

4 HomepageGross 跟 HomepageRollAndData是数据model,

5 RequestResultModel 请求数据结果

6 RequestResultUtil  处理请求的数据

  1 NetRequest 类
  2 
  3 /**
  4  * Created by liyongqiang on 15/6/11.
  5  */
  6 
  7 import  android.content.Context;
  8 import android.graphics.Bitmap;
  9 import android.support.v4.graphics.BitmapCompat;
 10 import android.util.LruCache;
 11 
 12 import com.android.volley.RequestQueue;
 13 import com.android.volley.toolbox.ImageLoader;
 14 import com.android.volley.toolbox.ImageLoader.ImageCache;
 15 import com.android.volley.toolbox.Volley;
 16 import com.loopj.android.http.AsyncHttpClient;
 17 import com.loopj.android.http.AsyncHttpRequest;
 18 import com.loopj.android.http.AsyncHttpResponseHandler;
 19 import com.loopj.android.http.JsonHttpResponseHandler;
 20 import com.loopj.android.http.RequestParams;
 21 import com.loopj.android.http.ResponseHandlerInterface;
 22 
 23 
 24 import org.apache.http.client.utils.URLEncodedUtils;
 25 
 26 public class NetRequest {
 27 
 28     private static NetRequest netRequest = null;
 29 
 30     // 图片加载
 31     private Context context;
 32     /** 上下文 */
 33     private Context content;
 34 
 35     /** 图片请求队列 */
 36     private RequestQueue imageRequestQ;
 37 
 38     /** 图片ImageLoader */
 39     private ImageLoader imageLoader;
 40 
 41     /** 图片缓存LRU */
 42     private ImageCache imageCache;
 43 
 44     /** LRU缓存的数量。为了防止溢出,一般不要超过60 */
 45    final LruCache<String,Bitmap> lruCache = new LruCache<String, Bitmap>(20);
 46 
 47     // 网路请求
 48     private AsyncHttpClient client;
 49 
 50 
 51     /* 构造函数 */
 52     // 图片加载构造函数
 53    private NetRequest(Context context){
 54         this.content = context;
 55         this.imageRequestQ = Volley.newRequestQueue(this.content);
 56         this.imageCache = new ImageCache() {
 57             @Override
 58             public Bitmap getBitmap(String s) {
 59                 return lruCache.get(s);
 60             }
 61             @Override
 62             public void putBitmap(String s, Bitmap bitmap) {
 63                 lruCache.put(s,bitmap);
 64             }
 65         };
 66         this.imageLoader = new ImageLoader(imageRequestQ, imageCache);
 67     };
 68 
 69     // 网路请求构造函数
 70     private  NetRequest(Context context, String request){
 71         this.client = new AsyncHttpClient();
 72         this.client.setTimeout(11000);
 73         this.content = context;
 74     }
 75 
 76 
 77 
 78     /** 单例模式 */
 79     // 图片单例
 80     public static NetRequest sharedNetRequestWithImage(Context context){
 81         if (netRequest == null){
 82             synchronized (NetRequest.class){
 83                 if(netRequest == null){
 84                     netRequest = new NetRequest(context);
 85                 }
 86             }
 87         }
 88         return netRequest;
 89     }
 90 
 91     // 数据请求单例
 92     public static NetRequest shareNetRequestWithRequest(Context context){
 93         if (netRequest == null){
 94             synchronized (NetRequest.class){
 95                 if(netRequest == null){
 96                     netRequest = new NetRequest(context,"request");
 97                 }
 98             }
 99         }
100         return netRequest;
101     }
102 
103     /**
104      * get 请求
105      * */
106     public void get_request_async(String urlStr,AsyncHttpResponseHandler res){
107         this.client.get(this.context,urlStr, res);
108     }
109 
110     public void get_request_json(String urlStr,JsonHttpResponseHandler res){
111         this.client.get(this.context, urlStr,res);
112     }
113 
114 
115     /**
116      * post 请求
117      * */
118     public void post_request_async(String urlStr,RequestParams params,AsyncHttpResponseHandler res){
119         this.client.post(this.context, urlStr, params, res);
120     }
121 
122     public void post_request_json(String urlStr, RequestParams params,JsonHttpResponseHandler res){
123         this.client.post(this.context, urlStr,params, res);
124     }
125 
126 
127     /** get set*/
128     public ImageLoader getImageLoader() {
129         return imageLoader;
130     }
131 }
NetUtil 类

/**
 * Created by liyongqiang on 15/6/11.
 */
public class NetUtil {

    public interface Request_call_back {
        /**
         * 请求返回的结果
         */
        public void request_back_result(RequestResultModel model);
    }


    /** 防止工具类被实例化 */

    public void NetUtil(){
        throw new AssertionError("不能实例化对象,数据请求NetUtil");
    }

    /*
    * 图片加载
    * */
    public static ImageContainer loafImage(Context content, String imageUrl,ImageView imageV,final int defaultImageResId, final int errorImageResId){
      NetRequest netRequest = NetRequest.sharedNetRequestWithImage(content);
      return netRequest.getImageLoader().get(imageUrl,ImageLoader.getImageListener(imageV, defaultImageResId, errorImageResId));
    }

    /**
     * get请求
     * */
    public static void get_request_async(String requestTag,Context context, String urlStr){
        NetRequest netRequest = NetRequest.shareNetRequestWithRequest(context);
        netRequest.get_request_async(urlStr, new AsyncHttpResponseHandler() {

            @Override
            public void onStart() {
                System.out.println("开始");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
                if (statusCode == 200) {

                } else {

                }
                System.out.println("成功" + statusCode + bytes);
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                System.out.println("失败");
            }

            @Override
            public void onFinish() {
                System.out.println("结束");
            }
        });
    }

    public static void get_request_json(final String requestTag,Context context,String urlStr){

        NetRequest netRequest = NetRequest.shareNetRequestWithRequest(context);
        netRequest.get_request_json(urlStr, new JsonHttpResponseHandler() {


                    @Override
                    public void onStart() {
                        System.out.println("开始");

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        System.out.println("成功" + statusCode + "数据" + response);

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        System.out.println("失败");
                    }

                    @Override
                    public void onFinish() {
                        System.out.println("结束");
                    }
                }
        );
    }


    /**
     *
     * post请求
     * */
    public static void  post_request_Async(String RequestTag, Context context, String urlStr, RequestParams params){
        NetRequest netRequest = NetRequest.shareNetRequestWithRequest(context);
        netRequest.post_request_async(urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                System.out.println("开始");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
                if (statusCode == 200) {

                } else {

                }
                System.out.println("成功" + statusCode + bytes);
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                System.out.println(i + "失败" + throwable);
            }

            @Override
            public void onFinish() {
                System.out.println("结束");
            }
        });
    }


    public static void post_request_Json(final String requestTag, final Context context, String urlStr, final RequestParams params, final Request_call_back request_call_back){
        NetRequest netRequest = NetRequest.shareNetRequestWithRequest(context);
        netRequest.post_request_json(urlStr, params, new JsonHttpResponseHandler() {
            @Override
            public void onStart() {
                    request_call_back.request_back_result(RequestResultUtil.request_handle_result(null, requestTag, DataRequestMacro.kResultStart));

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                System.out.println("statusCode"+statusCode);
                if(statusCode == 200){
                    request_call_back.request_back_result(RequestResultUtil.request_handle_result(response, requestTag, DataRequestMacro.kResultSucceess));
                }else {
                    request_call_back.request_back_result(RequestResultUtil.request_handle_result(null, requestTag, DataRequestMacro.kResultFail));
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                request_call_back.request_back_result(RequestResultUtil.request_handle_result(null, requestTag, DataRequestMacro.kResultFail));
            }

            @Override
            public void onFinish() {
                    request_call_back.request_back_result(RequestResultUtil.request_handle_result(null, requestTag, DataRequestMacro.kResultFinish));
            }
        });
    }

    /*
    * 处理链接
    * */
    public static RequestParams params_route_data(Map routeMap,Map dataMap){
        RequestParams requestParams = new RequestParams();
        requestParams.put("power",DataRequestMacro.kPowerStr);
        if (routeMap != null){
            JSONObject routeObj = new JSONObject(routeMap);
            requestParams.put("route",routeObj);
        }
        if (dataMap != null){
            JSONObject dataObj = new JSONObject(dataMap);
            requestParams.put("data", dataObj);
        }
     return requestParams;
    }

 

RequestResultModel 请求的结果
/**
 * Created by liyongqiang on 15/6/16.
 */
public class RequestResultModel {
    public int resultCode;
    public String requestTag;
    public String status;
    public Object data;
}

 

RequestResultUtil  数据处理
/**
 * Created by liyongqiang on 15/6/16.
 */
public class RequestResultUtil {

    public RequestResultUtil(){
        throw new AssertionError("不能实例化对象");
    }

    public static RequestResultModel request_handle_result(JSONObject response, String reqeuestTag,int statusCode) {
    if (reqeuestTag.equals(DataRequestMacro.kTagHomePageRoll)){
       return homepageRollModel(response,reqeuestTag,statusCode);
    } return null;
    }


    /*
    * 首页轮播数据model处理
    * */
    private static RequestResultModel homepageRollModel(JSONObject response, String requestTag,int statusCode){
        RequestResultModel model = new RequestResultModel();
        model.requestTag = requestTag;
        model.resultCode = statusCode;

        if (statusCode == DataRequestMacro.kResultSucceess){
            JSONObject resMap = response;
            JSONArray srollList = null;
            JSONObject statisticsMap = null;
            String stutas = null;
            HomepageGross gross = new HomepageGross();
            ArrayList list = new ArrayList();
            HashMap map = new HashMap();
            try {
                srollList = (JSONArray)resMap.get("scroll");
                statisticsMap = (JSONObject)resMap.get("statistics");
                stutas = (String)resMap.get("status");
                gross.clinic = (String)statisticsMap.get("clinic");
                gross.doctor = (String)statisticsMap.get("doctor");
                gross.groupon = (String)statisticsMap.get("groupon");
                gross.goods = (String)statisticsMap.get("goods");
            } catch (JSONException e) {
                e.printStackTrace();
            }
               for (int i=0;i<srollList.length();i++){
                   JSONObject scrollMap = null;
                   HomepageRollAndData rollAndData = new HomepageRollAndData();

                   try {
                       scrollMap = (JSONObject)srollList.get(i);
                       rollAndData.src = (String)scrollMap.get("src");
                       rollAndData.href = (String)scrollMap.get("href");
                   }catch (JSONException e){

                   }
                   list.add(rollAndData);
               }
               map.put("status", stutas);
               map.put("scroll", list);
               map.put("statistics",gross);
               model.data = map;
        }
        return model;
    }

    /*
    * 有页面社区
    * */

    public static RequestResultModel homepageComModel(JSONObject response, String requestTag,int statusCode){
        return null;
    }

 

感觉封装完简单了很多,有没有。

 1 开始请求
 2  Map routeDict =new HashMap();
 3         routeDict.put(DataRequestMacro.kFunction,DataRequestMacro.kHomepageRoll);
 4         routeDict.put(DataRequestMacro.kCHomepageIndex,DataRequestMacro.kClass);
 5         JSONObject routeStr = new JSONObject(routeDict);
 6 
 7         Map dataDict = new HashMap();
 8         dataDict.put(DataRequestMacro.kHomepageCity, "北京");
 9         JSONObject  dataStr = new JSONObject(dataDict);
10         
11         NetUtil.post_request_Json(DataRequestMacro.kTagHomePageRoll, this, DataRequestMacro.kRequestUrlstr, NetUtil.params_route_data(routeDict, dataDict), this);
12 
13 请求完数据回调。。。。
14 @Override
15     public void request_back_result(RequestResultModel model){
16         System.out.println("回调~~~~~~~~~~~~~~~~~~"+model.requestTag+model.resultCode);
17     }

开发IOS的刚开发Android 有什么不对的,你有什么更好的call me。一同进步。。谢谢

Android封装数据请求AsyncHttpClient 和 Volley

标签:

原文地址:http://www.cnblogs.com/IT-xiao-jian/p/4581523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!