Volley之简单封装(1)

本文对Volley简单封装,本文只是记录volley的使用

主要实现加载视图与请求分开:

数据回调的class

public abstract class CallBack {

    protected void onFail(int errCode,String errMsg) {
        //TODO 请求失败处理
        finish();
    }

    public abstract void onSuccess(JSONObject json) throws JSONException;

    public void start(){
    //开始请求,出现加载进度条
    }
    public void finish(){
    //请求结束,隐藏进度条
    }
}

单例请求class:

public class HttpUtils {
    private static HttpUtils ourInstance = new HttpUtils();
    private RequestQueue requestQueue = Volley.newRequestQueue(App.app);

    public static HttpUtils getInstance() {
        return ourInstance;
    }

    private HttpUtils() {
    }

    //根据需求添加重载方法
    public void Post( String url, final Map<String,String> map, final CallBack callBack) {
        makeRequest(Request.Method.POST,url,map,callBack,null);
    }

    private void makeRequest(int method, String url, final Map<String,String> map,
                            final CallBack callBack, Object tag){
        if (callBack != null) {
            callBack.start();
        }
        final StringRequest request = new StringRequest(method, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if (callBack != null) {
                        int code = object.getInt("code");
                        if (code == 0) {
                            callBack.onSuccess(object);
                              callBack.finish();
                        }else
                            callBack.onFail(null,code,object.getString("errMsg"));
                    }
                } catch (JSONException e) {
                    callBack.onFail(null,-1,"读取服务器数据失败");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (callBack!=null)
                    callBack.onFail(null,-2,"请求服务器失败");
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                if (map != null)
                    return map;
                return super.getParams();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        if (tag!=null) {
            request.setTag(tag);
        }
        requestQueue.add(request);
    }

    public void cancelRequest(@NotNull Object tag){
        requestQueue.cancelAll(tag);
    }


    public static final class RequestBuilder{
        private int method = Request.Method.POST;
        private String url;
        private Map<String,String> map;
        private CallBack callBack;
        private Object tag;

        public void build(){
            if (method == Request.Method.GET && map!=null){
                url=url+"?";
                for (String key:map.keySet()) {
                    try {
                        url=url+key+"="+ URLEncoder.encode(map.get(key),"UTF-8")+"&";
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                url = url.substring(0, url.length()-1);
            }
            HttpUtils.getInstance().makeRequest(method,url,map,callBack,tag);
        }

        public RequestBuilder bindMethod(int method){
            this.method = method;
            return this;
        }

        public RequestBuilder bindMap(Map<String,String> map){
            this.map = map;
            return this;
        }

        public RequestBuilder bindCallBack( CallBack callBack){
            this.callBack = callBack;
            return this;
        }

        public RequestBuilder bindTag( Object tag){
            this.tag = tag;
            return this;
        }
    }
}

使用方式:

        new HttpUtils.RequestBuilder().bindMap(new HashMap<String, String>())
                .bindTag("")
                .bindCallBack(new CallBack() {
                    @Override
                    public void onSuccess(JSONObject json) throws JSONException {

                    }
                }).build();

        //---------------或者下面这个方式-------------

         HttpUtils.getInstance().Post("url", new HashMap<String, String>(), new CallBack() {
            @Override
            public void onSuccess(JSONObject json) throws JSONException {

            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值