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);