天天看點

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 == ) {
                            callBack.onSuccess(object);
                              callBack.finish();
                        }else
                            callBack.onFail(null,code,object.getString("errMsg"));
                    }
                } catch (JSONException e) {
                    callBack.onFail(null,-,"讀取伺服器資料失敗");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (callBack!=null)
                    callBack.onFail(null,-,"請求伺服器失敗");
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                if (map != null)
                    return map;
                return super.getParams();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(, 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(, url.length()-);
            }
            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 {

            }
        });