首页 > 代码库 > volley 框架简易封装使用

volley 框架简易封装使用

给自己留个记录 仅仅是请求数据的

import android.app.Dialog;
import android.content.Context;
import android.util.Log;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mohism.jiayouchina.JiaYouApplication;

import java.util.Map;

import utils.GsonUtil;
import utils.StringUtil;

/**
 * @author liugongce
 */
public class HttpSender {
    private String mRequestUrl = "";
    private OnHttpResListener onHttpResListener;// 回调接口
    private String name = "http请求描述";// 请求描述
    private Object mRequestObj = null;
    private String firstCharForGetRequest = "?";
    private boolean isShowDialog;
    private Dialog dialog;
    private Context context;
    private String encoding ;
    public int connectTimeOut = 20 * 1000;
    private String tag;
    private MyStringRequest request = null;
    private Map<String, String> map;
    private int what;//给线程加标记
    // -------------------------------------------构造函数--------------------------------------------------------

    private HttpSender(Builder builder) {
        this.mRequestUrl = builder.mRequestUrl;
        this.onHttpResListener = builder.onHttpResListener;
        this.name = builder.name;
        this.mRequestObj = builder.mRequestObj;
        this.isShowDialog = builder.isShowDialog;
        this.context = builder.context;
        this.connectTimeOut = builder.connectTimeOut;
        this.encoding=builder.enCoding;
        this.what=builder.what;
        this.dialog=builder.dialog;
        this.tag = (builder.tag == null || builder.tag.equals("")) ? "abctag" : tag;
    }

    // -------------------------------------------------公开调用方法------------------------------------------

    /**
     * post请求
     */
    public void sendPost() {
        if(NetUtils.isNetworkConnected(context)) {
            request(0);
        }else{
            if (onHttpResListener != null) {
                onHttpResListener.noInternet();
            }
        }
    }

    /**
     * get请求
     */
    public void sendGet() {
        if(NetUtils.isNetworkConnected(context)) {//如果有网络
            request(1);
        }else {
            if (onHttpResListener != null) {
                onHttpResListener.noInternet();
            }
        }
    }
    // --------------------------------------------回调操作------------------------------------------------

    /**
     * 请求成功回调
     */
    private Response.Listener<String> succListener = response -> {
        dismissDialog();
        if (onHttpResListener != null) {
            onHttpResListener.doSuccess(response,what);
        }
    };
    /**
     * 请求失败的回调
     */
    private Response.ErrorListener errListener = error -> {
        dismissDialog();
        if (onHttpResListener != null) {
            onHttpResListener.otherError(error,what);
        }
    };

    // ------------------------------------------------请求操作----------------------------------------------
    private void request(int method) {
        if (StringUtil.isBlank(mRequestUrl)) {
            Log.i("Info", name + "POST请求 Url为空");
            return;
        }
        if (mRequestObj != null) {
            String json = GsonUtil.getInstance().toJson(mRequestObj);
            map = new Gson().fromJson(json, new TypeToken<Map<String, String>>() {
            }.getType());
        }
        if (method == 0) {//post请求

            request = new MyStringRequest(com.android.volley.Request.Method.POST, mRequestUrl, succListener, errListener,encoding) {
                @Override
                protected Map<String, String> getParams() {
                    return map;
                }
            };
            Log.i("Info", "POST请求名称: " + name + "POST请求Url: "
                    + mRequestUrl.toString());
                if(map!=null) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        String key = entry.getKey().trim();
                        String value = entry.getValue().toString().trim();
                        Log.i("Info", "POST提交参数: " + key + " = " + value);//打印信息
                    }
                }
        } else {//get请求
            StringBuilder sb = new StringBuilder(mRequestUrl);
            if (mRequestUrl.contains("?")) {
                firstCharForGetRequest = "&";
            }
            sb.append(firstCharForGetRequest);
            if(map!=null) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    String key = entry.getKey().trim();
                    String value = entry.getValue().toString().trim();
                    sb.append(key + "=" + value.toString());
                    sb.append("&");
                }
                sb.deleteCharAt(sb.length() - 1);
            }
            request = new MyStringRequest(Request.Method.GET, sb.toString(), succListener, errListener,encoding);
            Log.i("Info", "GET请求名称: " + name + "GET请求Url: " + sb.toString());//打印信息
        }
        request.setRetryPolicy(new DefaultRetryPolicy(connectTimeOut, 1, 1.0f));//设置请连接超时时间
        request.setTag(tag);
        JiaYouApplication.mInstance.getRequestQueue().add(request);
        showDialog();
    }


    /**
     * 显示等待对话框
     */
    public void showDialog() {
        try {
            if (!isShowDialog) {
                return;
            }
            if(dialog!=null&&!dialog.isShowing()){
                dialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭等待对话框
     */
    public void dismissDialog() {
        try {
            if (dialog != null && dialog.isShowing())
                dialog.dismiss();
        } catch (Exception e) {
        }
    }

    public static class Builder {
        private String mRequestUrl = "";
        private OnHttpResListener onHttpResListener;// 回调接口
        private String name = "http请求描述";// 请求描述
        private Object mRequestObj = null;
        private boolean isShowDialog;
        private Context context;
        private String enCoding="UTF-8";
        public int connectTimeOut = 20 * 1000;
        private String tag;
        private int what=-1;
        private Dialog dialog;
        public  Builder(Context context){
            this.context=context;
        }
        /**
         * @param mRequestUrl 请求地址
         * @return
         */
        public Builder setRequestUrl(String mRequestUrl) {
            this.mRequestUrl = mRequestUrl;
            return this;
        }

        /**
         * 请求接口标记
         *
         * @param name
         * @return
         */
        public Builder setRequestName(String name) {
            this.name = name;
            return this;
        }

        /**
         * @param mRequestObj 参数(可以是实体类对象,也可以是一个Map对象)
         * @return
         */
        public Builder setRequestParams(Object mRequestObj) {
            this.mRequestObj = mRequestObj;
            return this;
        }
        /**
         * @param connectTimeOut 设置连接超时时间
         * @return
         */
        public Builder setConnectTimeOut(int connectTimeOut) {
            this.connectTimeOut = connectTimeOut;
            return this;
        }

        /**
         * @param tag 设置标签,对请求进行标记
         * @return
         */
        public Builder setRequestTag(String tag) {
            this.tag = tag;
            return this;
        }

        /**
         * @return 设置请求编码 默认UTF-8
         */
        public Builder setRequestEncoding(String enCoding){
            this.enCoding=enCoding;
            return this;
        }
        /**
         * @param onHttpResListener 设置回调监听
         * @return
         */
        public Builder setOnHttpListener(OnHttpResListener onHttpResListener) {
            this.onHttpResListener = onHttpResListener;
            return this;
        }

        /**
         * @param dialog 设置想要显示的弹出框
         * @return
         */
        public Builder setDialog(Dialog dialog){
            this.dialog=dialog;
            return this;
        }
        /**
         * @param what 给每个请求打上标记,为了区分在同一个页面中的多个请求
         * @return
         */
        public Builder setWhat(int what){
            this.what=what;
            return  this;
        }
        /**
         * @return 返回一个请求对象
         */
        public HttpSender build() {
            return new HttpSender(this);
        }

    }
}

调用方法

 getBaseMapWithUid();
        baseMap.put("p", p + "");
        baseMap.put("nums", nums + "");
        baseMap.put("status", status + "");
        new HttpSender.Builder(getActivity())
                .setRequestUrl(Urls.GetUserOrder)
                .setRequestParams(baseMap)
                .setRequestName("获取订单")
                .setWhat(0x123)
                .setRequestTag("OrderRequest")
                .setOnHttpListener(new OnHttpResListenerIml() {
                    @Override
                    public void doSuccess(String data, int what) {
                     //请求成功处理代码       
        

                    }
                }).build().sendPost();            

 

volley 框架简易封装使用