网络请求代理 HttpProcessor

来自动脑学院-框架搭建重构
用于管理网络请求,方便替换网络请求框架

//请求返回基类
public interface ICallback {
    void onSuccess(String result);
    void onFailure(String e);
}

//Gson请求返回基类
public abstract class HttpCallback  implements ICallback {
    @Override
    public void onSuccess(String result){
        Gson gson = new Gson();
        Class clz =analysisClassInfo(this);
        Result objRsult = (Result) gson.fromJson(result, clz);
        onSuccess(objRsult);
    }

    protected abstract void onSuccess(Result objRsult);

    private Class analysisClassInfo(Object obj) {
        Type getType = obj.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType)getType).getActualTypeArguments();
        return (Class) params[0];
    }
}
//请求基类
public interface IHttpProcessor {
    void post(String url,Map params,ICallback callback);
    void get(String url,Map params,ICallback callback);
}

//Volley请求类
public class VolleyProcessor implements IHttpProcessor {

    private  static RequestQueue mQueue = null;

    public VolleyProcessor(Context context){
        mQueue = Volley.newRequestQueue(context);
    }

    @Override
    public void post(String url, Map params, final ICallback callback) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                callback.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callback.onFailure(error.getMessage());
            }
        }){
            @Override
            protected Map getParams() throws AuthFailureError {
                Map map=new HashMap<>();
                map.put("phone","13800138000");
                return map;
            }
        };
        mQueue.add(stringRequest);
    }

    @Override
    public void get(String url, Map params, final ICallback callback) {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                callback.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callback.onFailure(error.getMessage());
            }
        });
        mQueue.add(stringRequest);
    }
}
//请求代理类
public class HttpHelper implements IHttpProcessor {
    private static IHttpProcessor mIHttpProcessor = null;
    private static HttpHelper _instance;

    private HttpHelper() {
    }

    public static HttpHelper obtain() {
        synchronized (HttpHelper.class) {
            if (_instance == null) {
                _instance = new HttpHelper();
            }
        }
        return _instance;
    }

    public static void init(IHttpProcessor httpProcessor) {
        mIHttpProcessor = httpProcessor;
    }


    public void post(String url, Map params, ICallback callback) {
        final String finalUrl = appendParams(url, params);
        mIHttpProcessor.post(url, params, callback);
    }

    @Override
    public void get(String url, Map params, ICallback callback) {
        final String finalUrl = appendParams(url, params);
        System.out.println(finalUrl);
        mIHttpProcessor.get(finalUrl, params, callback);
    }


    private static String appendParams(String url, Map params) {
        if (params == null || params.isEmpty()) {
            return url;
        }

        StringBuilder urlBuilder = new StringBuilder(url);

        if (urlBuilder.indexOf("?") <= 0) {
            urlBuilder.append("?");
        } else if (!urlBuilder.toString().endsWith("?")) {
            urlBuilder.append("&");
        }
        for (Map.Entry entry : params.entrySet()) {
            urlBuilder.append(entry.getKey()).append("=").append(encode(entry.getValue().toString())).append("&");
        }
        return urlBuilder.toString();
    }

    private static String encode(String str) {
        try {
            return URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            Log.e("参数转码异常", e.toString());
            throw new RuntimeException(e);
        }
    }
}
//使用
 HttpHelper.init(new VolleyProcessor(this));//初始化,放在Application
        String url = "http://api.k780.com:88/?app=phone.get";

        HashMap map = new HashMap<>();
        map.put("phone","13800138000");
        map.put("appkey","10003");
        map.put("sign","b59bc3ef6191eb9f747dd4e83c99f2a4");
        map.put("format","json");
        HttpHelper.obtain().post(url, map, new HttpCallback() {
            @Override
            public void onSuccess(Bean bean) {
                System.out.println(bean.toString());
            }

            @Override
            public void onFailure(String e) {

            }
        });

你可能感兴趣的:(网络请求代理 HttpProcessor)