volley的增强写法

 

这种方法在请求时使用的是静态的RequestQueue,上下文从框架中获得全局的静态context,在进行循环请求的时候不会锁死context,可以解决oom问题

package com.lenovo.smarttraffic.util;

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

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.lenovo.smarttraffic.InitApp;

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

public class HttpUtils {
    private static RequestQueue requestQueue = Volley.newRequestQueue(InitApp.getContext());
    private JSONObject param = new JSONObject();
    private static final String TAG = "HttpUtils";

    //回调接口
    public interface CallBack {
        void success(JSONObject response) throws JSONException;
    }

    public interface StringCallBack {
        void success(String response) throws Exception;
    }

    //josn对象中添加参数
    public HttpUtils setParam(String name, Object object) {
        try {
            param.put(name, object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return this;
    }

    public JSONObject getParam() {
        return param;
    }

    public static void post(final Context context, String url, HttpUtils data, final CallBack callBack) {
        //请求的链接
        String strUrl = "http://" + "10.0.2.2" + ":" + "8080" + "/api/v2/" + url;
        Log.i(TAG, "post: " + strUrl + "        " + data.getParam().toString());
        //创建一个连接队列
        //需要请求的对象
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                strUrl,
                data.getParam(),    //post请求的json参数
                jsonObject -> {     //请求成功的回调
                    try {
                        callBack.success(jsonObject);   //调用回调
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, volleyError -> { //请失败的回调
            Toast.makeText(InitApp.getContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
        });
        //进行请求
        requestQueue.add(jsonObjectRequest);
    }

//    public static void diyGet(final Context context, String url, final StringCallBack callBack) {
//        //创建一个连接队列
//        RequestQueue requestQueue = Volley.newRequestQueue(context);
//        //需要请求的对象
//        StringRequest stringRequest = new StringRequest(Request.Method.GET,
//                url, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                try {
//                    callBack.success(s);   //调用回调
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }, volleyError -> { //请失败的回调
//            Toast.makeText(context, volleyError.toString(), Toast.LENGTH_LONG).show();
//        });
//        //进行请求
//        requestQueue.add(stringRequest);
//    }
//
//    public static void postBalance(final Context context, int carNumber, final CallBack callBack) {
//        post(context, "get_car_account_balance", new HttpUtils().setParam("CarId", carNumber).setParam("UserName", "test"), callBack);
//    }
}

完全体源码(尚未阅读)

package com.lenovo.smarttraffic.util;

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

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.Volley;

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

import java.util.HashMap;
import java.util.Map;
public class Http {
    private JSONObject param = new JSONObject();
    private static Map<Integer, Integer> len = new HashMap<>();
    private int id = 0;

    public Http setId(int id) {
        this.id = id;
        return this;
    }
    public int getId() {
        return id;
    }

    public Http setParam(String name, Object object) {
        try {
            this.param.put(name, object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return this;
    }

    public JSONObject getParam() {
        return param;
    }

    public interface CallBack {
        void success(JSONObject res, Http data) throws JSONException;
    }

    public static String username = "user1";
    private static RequestQueue mQueue;

    public static void post(final Context context, String url, final Http data, final CallBack callBack) {
        String strUrl = "http://" + "172.17.36.217" + ":" + "8080" + "/api/v2/" + url;
        data.setParam("UserName", username);
        Log.d("TAG", strUrl);
        len.put(data.getId(), len.get(data.id) == null ? 1 : len.get(data.id) + 1);
        if (mQueue == null) mQueue = Volley.newRequestQueue(context);
        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, strUrl, data.getParam(), new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        len.put(data.getId(), len.get(data.id) - 1);
                        Log.d("TAG", response.toString());
                        try {
                            callBack.success(response, data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
//                        Toast.makeText(context, response.optString("ERRMSG"), Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        len.put(data.getId(), len.get(data.id) - 1);
                        Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                    }
                });
        mQueue.add(jsonObjectRequest);
    }

    public static boolean isEnd(int... id) {
        for (int i = 0; i < id.length; i++) {
            if (len.get(id[i]) != null && len.get(id[i]) > 0) {
                return false;
            }
        }
        return true;
    }
}