一 。简介
volley 是 Goole I/O 2013上发布的网络通信库,使网络通信更快、更简单、更健壮。
关键词:数据不大但通信频繁
二。优点
- 非常适合进行数据量不大,但通信频繁的网络操作
- 可直接在主线程调用服务端并处理返回结果
- 可以取消请求,容易扩展,面向接口编程
- 网络请求线程NetworkDispatcher默认开启了4个,可以优化,通过手机CPU数量
- 通过使用标准的HTTP缓存机制保持磁盘和内存响应的一致
三。缺点
- 使用的是httpclient、HttpURLConnection
- 6.0不支持httpclient了,如果想支持得添加org.apache.http.legacy.jar
- 对大文件下载 Volley的表现非常糟糕
- 只支持http请求
- 图片加载性能一般
四。使用
在项目中网络请求是一个必须的功能,为了减少代码的重复,需要对volley进行二次封装。
https://blog.csdn.net/cai554112503/article/details/50096755
public class Appaplication extends Application {
private static RequestQueue queues;
@Override
public void onCreate() {
super.onCreate();
queues = Volley.newRequestQueue(getApplicationContext());
}
public static RequestQueue getQueues(){
return queues;
}
}
public abstract class VolleyInterface {
private Context context;
public Response.Listener<String> listener;
public Response.ErrorListener errorListener;
public VolleyInterface(Context context) {
this.context = context;
}
public abstract void onMySuccess(String result);
public abstract void onMyError(VolleyError error);
public Response.Listener<String> loadingListener() {
listener = new Response.Listener<String>() {
@Override
public void onResponse(String s) {
onMySuccess(s);
}
};
return listener;
}
public Response.ErrorListener errorListener() {
errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
onMyError(volleyError);
}
};
return errorListener;
}
}
public class Volleyutil {
public static StringRequest request;
private Context context;
/**
* get请求
* @param context
* @param url
* @param tag
* @param vif
*/
public static void RequestGet(Context context, String url, String tag,VolleyInterface vif) {
Appaplication.getQueues().cancelAll(tag);
request = new StringRequest(Request.Method.GET, url,vif.loadingListener(),vif.errorListener());
request.setTag(tag);
Appaplication.getQueues().add(request);
Appaplication.getQueues().start();
}
/**
* post请求
* @param context
* @param url
* @param tag
* @param params
* @param vif
*/
public static void RequestPost(Context context, String url, String tag, final Map<String,String> params, VolleyInterface vif) {
Appaplication.getQueues().cancelAll(tag);
request = new StringRequest(Request.Method.POST, url,vif.loadingListener(),vif.errorListener()){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
request.setTag(tag);
Appaplication.getQueues().add(request);
Appaplication.getQueues().start();
}
}
Map<String,String> map = new HashMap<>();
map.put("LOGIN_NUM", "gstb002");
map.put("PASSWORD", "123456");
Volleyutil.RequestPost(this,"http://192.168.10.55:8080/fdkj-restful/resources/user/login","MainActivity",map, new VolleyInterface(this) {
@Override
public void onMySuccess(String result) {
Log.d("tag",result);
}
@Override
public void onMyError(VolleyError error) {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
Appaplication.getQueues().cancelAll("MainActivity");
}