美文网首页
Volley使用详情

Volley使用详情

作者: 212_8faa | 来源:发表于2019-12-20 19:25 被阅读0次

1.Volley主要特点

  • 1.扩展性强:基于接口设计
  • 2.一定程度上符合HTTP规范,返回包括ResponseCode的处理、请求头处理、缓存机制的处理
  • 3.重试以及优先级的定义
  • 4.2.3以上使用HttpURLConnection2.3以下使用HttpClient
  • 5.提供简单的图片加载工具

2.Volley使用

1.导包
implementation'com.navercorp.volleyextensions:volley-requests:2.0.1'
2.创建RequestQueue
RequestQueue requestQueue = Volley.newRequestQueue(this.getApplicationContext());

可以自定义创建RequestQueue,控制返回结果是否在主线程

默认通过Volley创建的RequestQueue
public RequestQueue(Cache cache, Network network, int threadPoolSize) {
     this(cache, network, threadPoolSize, new ExecutorDelivery(new Handler(Looper.getMainLooper())));
}
自定义创建(自定创建时可以使返回结果不在UI线程处理)
public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) {
    mCache = cache;
    mNetwork = network;
    mDispatchers = new NetworkDispatcher[threadPoolSize];
    mDelivery = delivery;
}
3.String请求
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                 //处理返回结果(默认创建的RequestQueue在主线程)
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                 //处理返回错误信息(默认创建的RequestQueue在主线程)
            }
        });
requestQueue.add(request);
4.JSONObject请求
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonRequest, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
             //处理返回结果(默认创建的RequestQueue在主线程)
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
             //处理返回错误信息(默认创建的RequestQueue在主线程)
        }
    });
requestQueue.add(request);
5.自定义Request请求

定义类继承Request<T>,重写parseNetworkResponse函数可以结合JSON解析工具

@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
      //异步线程中处理返回数据解析
}
6.同步请求
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest("",future,future);
requestQueue.add(stringRequest);
String response = future.get();//该方法为同步方法,其中使用wait等待结果返回被notify
//String response = future.get(1500, TimeUnit.MILLISECONDS);//设置超时时间

3.总结

Volley适合数据量小,通信频繁的网络操作。android绝大多数都属于这种类型,但是对于数据量比较大的操作,比如:下载,就不太适用了。

相关文章

网友评论

      本文标题:Volley使用详情

      本文链接:https://www.haomeiwen.com/subject/gbiinctx.html