对Volley框架进行封装,以便于更好地使用Volley。

1.首先使用静态内部类的方法创建一个单例。

public class MyVolley {
    private static MyVolley myVolley;

    public static MyVolley newMyVolley(){
        if (myVolley==null){
            myVolley=new MyVolley();
        }
        return myVolley;
    }
    .
    .
    .

}

2.然后定义一些变量,之后会定义get请求和post请求两个方法。

    private CallBack callback;
    private StringRequest stringRequest;
    private Context context;
    //String Get
    public void StringRequestGet(Context context,String url,CallBack callback){
        this.context=context;
        RequestQueue requestQueue= Volley.newRequestQueue(context);
        this.callback=callback;
        stringRequest=new StringRequest(Request.Method.GET,url,stringListener,errorListener);
        requestQueue.add(stringRequest);
    }
    //String post
    public void StringRequestPost(Context context, String url,final Map map,CallBack callback){
        RequestQueue requestQueue=Volley.newRequestQueue(context);
        this.callback=callback;
        stringRequest=new StringRequest(Request.Method.POST,url,stringListener,errorListener){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }
        };
    }

3.在里面重写两个监听事件

private Response.Listener<String> stringListener=new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            callback.onStringSuccess(response);
        }
    };
    //error listener
    private Response.ErrorListener errorListener=new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            callback.onFailure(error);
        }
    };

4.定义Callback的两个接口。

public interface CallBack{

        public void onStringSuccess(String Response);
        public void onFailure(VolleyError error);
    }

下面实在具体方法中调用的例子。

String Key=model.toUtf8String(key); 
Stringurl="http://apis.juhe.cn/cook/query.phpdtype=&pn=&rn=&albums=&key=ea5611294c5c8871a6845467a74e77ab&menu="+Key; 
MyVolley myVolley=new MyVolley(); myVolley.StringRequestGet(context,url,this);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值