对Volley简单的封装,让网络请求更简单

——–安卓初学者,大神轻喷

在项目中需要网络请求,找了很多框架,发现volley算是比较好用的了,可是每次请求带的参数又多又乱,于是进行了简单的整理,方便使用。

首先添加volley的依赖库(可能不是最新版,建议搜索最新版使用)

compile ‘com.mcxiaoke.volley:library:1.0.19’

现在的网络请求大多数都是json格式的,所以只进行了jsonRequest的使用。

post

RequestQueue requestQueue = Volley.newRequestQueue(context);
                JsonRequest request = new JsonObjectRequest(Request.Method.POST, url, jsondata, new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                                           }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {


                               }
                }) {
                    @Override
                    public Map getHeaders() throws AuthFailureError {
                        HashMap headers = new HashMap();
                        headers.put("Accept", "application/json");
                        headers.put("Content-Type", "application/json; charset=UTF-8");
                        return headers;

                    }
                };
                requestQueue.add(request);
            }

这就是volley的post请求,看起来是不是又乱又麻烦,强迫症的我根本不能接受,于是在很简单的改动后,代码变成了这样,虽然更多了,但是一劳永逸啊

public static class Post {
        private Context context;
        private JSONObject data = null;
        private String url = "";
        private OnPostListener onPostListener;

        public Post(Context context) {
            this.context = context;
        }

        public Post setData(JSONObject data) {
            this.data = data;
            return this;
        }

        public Post setUrl(String url) {
            this.url = url;
            return this;
        }

        public Post post() {
            if (data == null)
                data = new JSONObject();
            if (url.equals("")) {
                onPostListener.Failed("请设置url");
            } else {
                RequestQueue requestQueue = Volley.newRequestQueue(context);
                JsonRequest request = new JsonObjectRequest(Request.Method.POST, url, data, new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (onPostListener != null)
                            onPostListener.Success(response.toString());
                        i(response.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (onPostListener != null)
                            onPostListener.Failed(error.toString());
                        e(error.toString());
                    }
                }) {
                    @Override
                    public Map getHeaders() throws AuthFailureError {
                        HashMap headers = new HashMap();
                        headers.put("Accept", "application/json");
                        headers.put("Content-Type", "application/json; charset=UTF-8");
                        return headers;

                    }
                };
                requestQueue.add(request);
            }
            return this;
        }

        public void setOnPostListener(OnPostListener onPostListener) {
            this.onPostListener = onPostListener;
        }

接口:

public interface OnPostListener {
        void Success(String result);

        void Failed(String msg);
    }

好了,经过这样的改变,使用起来也顺手多了呢,只需简单的几行代码,便可完成一次post请求:

 new Post(context).setData(jsondata).setUrl(url).post().setOnPostListener(new OnPostListener() {
            @Override
            public void Success(String result) {
                            }

            @Override
            public void Failed(String msg) {

            }
        });

get方法也是同理,因为这种代码很少修改,所以博主把post和get的方法放到了同一class中,源代码:

package com.smple.eshutao_new.netmodule.base;

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

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by simple on 2016/10/16.
 */
public class C {
    public static class Post {
        private Context context;
        private JSONObject data = null;
        private String url = "";
        private OnPostListener onPostListener;

        public Post(Context context) {
            this.context = context;
        }

        public Post setData(JSONObject data) {
            this.data = data;
            return this;
        }

        public Post setUrl(String url) {
            this.url = url;
            return this;
        }

        public Post post() {
            if (data == null)
                data = new JSONObject();
            if (url.equals("")) {
                onPostListener.Failed("请设置url");
            } else {
                RequestQueue requestQueue = Volley.newRequestQueue(context);
                JsonRequest request = new JsonObjectRequest(Request.Method.POST, url, data, new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (onPostListener != null)
                            onPostListener.Success(response.toString());
                        i(response.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (onPostListener != null)
                            onPostListener.Failed(error.toString());
                        e(error.toString());
                    }
                }) {
                    @Override
                    public Map getHeaders() throws AuthFailureError {
                        HashMap headers = new HashMap();
                        headers.put("Accept", "application/json");
                        headers.put("Content-Type", "application/json; charset=UTF-8");
                        return headers;

                    }
                };
                requestQueue.add(request);
            }
            return this;
        }

        public void setOnPostListener(OnPostListener onPostListener) {
            this.onPostListener = onPostListener;
        }
    }

    public static class Get {
        private Context context;
        private String url;
        private OnGetListener onGetListener;

        public Get(Context context) {
            this.context = context;
        }

        public Get setUrl(String url) {
            this.url = url;
            return this;
        }

        public Get get() {
            if (url.equals("")) {
                onGetListener.Failed("请设置url");
            } else {
                RequestQueue requestQueue = Volley.newRequestQueue(context);
                JsonRequest request = new JsonObjectRequest(Request.Method.GET, url, new JSONObject(), new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (onGetListener != null)
                            onGetListener.Success(response.toString());
                        i(response.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        if (onGetListener != null)
                            onGetListener.Failed(error.toString());
                        e(error.toString());
                    }
                }) {
                    @Override
                    public Map getHeaders() throws AuthFailureError {
                        HashMap headers = new HashMap();
                        headers.put("Accept", "application/json");
                        headers.put("Content-Type", "application/json; charset=UTF-8");
                        return headers;

                    }
                };
                requestQueue.add(request);
            }
            return this;
        }

        public void setOnGetListener(OnGetListener onGetListener) {
            this.onGetListener = onGetListener;
        }
    }

    public interface OnPostListener {
        void Success(String result);

        void Failed(String msg);
    }

    public interface OnGetListener {
        void Success(String result);

        void Failed(String msg);
    }

    private static void i(String i) {
        Log.i("成功", i);
    }

    private static void e(String e) {
        Log.e("失败", e);
    }
}

你可能感兴趣的:(安卓开发,android)