使用Android Volley网络请求框架请求数据步骤

时间:2021-08-26 19:47:10

1、需要导入volley的jar包

2、使用实例

使用Volley必须在AndroidManifest.xml中添加 android.permission.INTERNET权限,使用Volley时Google建议创建volley单例工具类

package cn.hnshangyu.officeautomationsystem.net;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

/**
 * Created by Administrator on 2016/10/17
 */
public class VolleySingleton {
    private static VolleySingleton volleySingleton;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private Context mContext;

    public VolleySingleton(Context context) {
        this.mContext = context;
        mRequestQueue = getRequestQueue();
        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized VolleySingleton getVolleySingleton(Context context) {
        if (volleySingleton == null) {
            volleySingleton = new VolleySingleton(context);
        }
        return volleySingleton;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}

3、封装Response.Listener

package cn.hnshangyu.officeautomationsystem.net;

import com.android.volley.Response;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2016/10/27.
 * <p>
 * 请求服务器获得的数据
 */

public abstract class DefaultListener<T> implements Response.Listener<String> {

    @Override
    public void onResponse(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            String code = jsonObject.optString("retcode");
            String msg = "";
            if (code.equals("0")) {
                String data = "";
                if (jsonObject.has("data")) {
                    data = jsonObject.optString("data");
                    onSuccess(0, data);
                } else {
                    onSuccess(0, "");
                }
            } else {
                if (jsonObject.has("mesg")) {
                    msg = jsonObject.optString("mesg");
                } else {
                    msg = "对不起,服务器返回数据有错误!";
                }
                onResponseFailed(1, msg, new RuntimeException(msg));
            }
        } catch (JSONException e) {

            e.printStackTrace();
            onResponseFailed(2, "数据解析失败!", e);
        }
    }

    public abstract void onSuccess(int code, String data);

    public abstract void onResponseFailed(int code, String errorMsg, Exception e);
}

4、封装Response.ErrorListener

package cn.hnshangyu.officeautomationsystem.net;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;

/**
 * Created by Administrator on 2016/10/27.
 * 请求数据错误信息
 */

public abstract class DefaultErrorListener implements Response.ErrorListener {
    @Override
    public void onErrorResponse(VolleyError volleyError) {
        String errorMesg = "";
        if (volleyError instanceof NetworkError) {
            errorMesg = "网络连接失败";
        } else if (volleyError instanceof ServerError) {
            errorMesg = "服务器的响应错误";
        } else if (volleyError instanceof AuthFailureError) {
            errorMesg = "请求身份验证错误";
        } else if (volleyError instanceof ParseError) {
            errorMesg = "服务器返回数据有误";
        } else if (volleyError instanceof NoConnectionError) {
            errorMesg = "网络连接失败";
        } else if (volleyError instanceof TimeoutError) {
            errorMesg = "服务器太忙或网络延迟";
        }
        onErrorResponseFailed(errorMesg, volleyError);
    }

    protected abstract void onErrorResponseFailed(String errorMesg, VolleyError volleyError);
}

5、构建网络请求接口

    package cn.hnshangyu.officeautomationsystem.net;

    import android.content.Context;

    import com.android.volley.Response;

    import java.util.Map;

    /**
     * Created by Administrator on 2016/10/27.
     */

    public interface VolleyHttpClient {
        String HOST = "http://soft.********.org/";
        /**
         * 通讯录
         */
        String AppSysUserController = HOST + "/app/user/treeDept.json";

        /**
         * 得到好友通讯录
         *
         * @param tag
         * @param context
         * @param map
         * @param listener
         * @param errorListener
         */
        void getAppSysUserController(String tag, Context context, Map<String, String> map, DefaultListener<String> listener,
                                     DefaultErrorListener errorListener);

    }

6、构建HttpApi使用类 我们一般使用Post请求

package cn.hnshangyu.officeautomationsystem.net;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.Map;

/**
 * Created by Administrator on 2016/10/27.
 */

public class VolleyHttpApi implements VolleyHttpClient {

    private StringRequest stringRequest;
    private static VolleyHttpApi mInstance;
    private RequestQueue mRequestQueue;

    public static VolleyHttpApi getInstance() {
        if (mInstance == null) {
            synchronized (VolleyHttpApi.class) {
                if (mInstance == null)
                    mInstance = new VolleyHttpApi();
            }
        }
        return mInstance;
    }

    /**
     * POST 请求网络
     *
     * @param tag
     * @param context
     * @param url
     * @param map
     * @param listener
     * @param errorListener
     */
    private void getStringRequest(String tag, Context context, String url, final Map<String, String> map, DefaultListener<String> listener, DefaultErrorListener errorListener) {
        stringRequest = new StringRequest(Request.Method.POST, url, listener, errorListener) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }
        };

        VolleySingleton volleySingleton = VolleySingleton.getVolleySingleton(context);
        //获得队列
        mRequestQueue = volleySingleton.getRequestQueue();
        //添加tag
        stringRequest.setTag(tag);
        //将StringRequest对象添加进RequestQueue请求队列中
        mRequestQueue.add(stringRequest);

    }

    /**
     * Activity的onStop()方法
     * 取消网络请求
     *
     * @param tag
     */
    public void cancelQueue(String tag) {
        if (null != mRequestQueue) {
            mRequestQueue.cancelAll(tag);
        }
    }

    /**
     * 得到好友通讯录
     *
     * @param tag
     * @param context
     * @param map
     * @param listener
     * @param errorListener
     */
    @Override
    public void getAppSysUserController(String tag, Context context, Map<String, String> map, DefaultListener<String> listener, DefaultErrorListener errorListener) {
        getStringRequest(tag, context, AppSysUserController, map, listener, errorListener);
    }
}

7、在BaseActivity的onCreate方法中初始化网络请求

      /**
     * 初始化网络请求
     */
    protected VolleyHttpApi volleyHttp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        synchronized (activities) {
            activities.add(this);
        }
        mActivity = this;
        mContext = this;

        volleyHttp = VolleyHttpApi.getInstance();

    }

8、在需要的地方请求数据

 private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("sessionId", "402880ec57fb58460157fb604cbc0000");
        volleyHttp.getAppSysUserController(tag, mContext, map, new DefaultListener<String>() {
            @Override
            public void onSuccess(int code, String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String dept = jsonObject.optString("dept");
                    LogUtil.i(dept);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onResponseFailed(int code, String errorMsg, Exception e) {
                UIUtils.showToast(errorMsg);
            }
        }, new DefaultErrorListener() {
            @Override
            protected void onErrorResponseFailed(String errorMesg, VolleyError volleyError) {
                UIUtils.showToast(errorMesg);
            }
        });
    }

9、取消网络连接

@Override
    protected void onStop() {
        super.onStop();
        if (null != volleyHttp)
            volleyHttp.cancelQueue(tag);
    }