Volley请求框架的使用

Volley是Google I/O 2013上提出来的为Android提供简单快速网络访问的项目。

Volley特别适合数据量不大但是通信频繁的场景。

优点
相比其他网络载入类库,Volley 的优势官方主要提到如下几点:
1、队列网络请求,并自动合理安排何时去请求;
2、提供了默认的磁盘和内存等缓存(Disk Caching & Memory Caching)选项;
3、Volley可以做到高度自定义,它能做到的不仅仅是缓存图片等资源;
4、Volley相比其他的类库更方便调试和跟踪;
5、可以取消请求,容易扩展,面向接口编程;
缺点
1、对大文件下载 Volley的表现非常糟糕;
2、只支持http请求;
3、图片加载性能一般;
4、使用的是Httpclient和HttpURLConnection。不过在android 6.0不支持Httpclient了,如果想支持得添加org.apache.http.legacy.jar;

Volley提供的功能
简单的讲,提供了如下主要的功能:
1、封装了的异步的RESTful 请求API;
2、一个优雅和稳健的请求队列;
3、一个可扩展的架构,它使开发人员能够实现自定义的请求和响应处理机制;
4、能够使用外部HTTP Client库;
5、缓存策略;
6、自定义的网络图像加载视图(NetworkImageView,ImageLoader等);

怎样使用Volley

这篇博客将会详细的介绍在应用程程中怎么使用volley,它将包括一下几方面:
1、安装和使用Volley库
2、使用请求队列
3、异步的JSON、String请求
4、取消请求
5、请求失败的重试次数,自定义请求超时时间
6、设置请求头(HTTP headers)
7、使用Cookies
8、错误处理

1、安装和使用Volley库
Volley开源库地址:https://github.com/google/volley
引入Volley非常简单,可以下载编译好的jar包放到工程的libs目录引入,Android Studio环境也可以直接在build.gradle文件中引入。
jar包下载地址:http://mvnrepository.com/artifact/com.android.volley/volley
build.gradle文件引入:

dependencies {
    ...
    compile 'com.android.volley:volley:1.1.1'
}

2、使用请求队列
Volley的所有请求都放在一个队列,然后进行处理,创建一个请求队列:

RequestQueue mRequestQueue = Volley.newRequestQueue(this);

理想的情况是把请求队列集中放到一个地方,最好是初始化应用程序类中初始化请求队列,下面类做到了这一点:

public class ApplicationController extends Application {

    /**
     * Log or request TAG
     */
    public static final String TAG = "VolleyPatterns";

    /**
     * Global request queue for Volley
     */
    private RequestQueue mRequestQueue;

    /**
     * A singleton instance of the application class for easy access in other places
     */
    private static ApplicationController sInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        // initialize the singleton
        sInstance = this;
    }

    /**
     * @return ApplicationController singleton instance
     */
    public static synchronized ApplicationController getInstance() {
        return sInstance;
    }

    /**
     * @return The Volley Request queue, the queue will be created if it is null
     */
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    /**
     * Adds the specified request to the global queue, if tag is specified
     * then it is used else Default TAG is used.
     *
     * @param req
     * @param tag
     */
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        VolleyLog.d("Adding request to queue: %s", req.getUrl());

        getRequestQueue().add(req);
    }

    /**
     * Adds the specified request to the global queue using the Default TAG.
     *
     * @param req
     * @param tag
     */
    public <T> void addToRequestQueue(Request<T> req) {
        // set the default tag if tag is empty
        req.setTag(TAG);

        getRequestQueue().add(req);
    }

    /**
     * Cancels all pending requests by the specified TAG, it is important
     * to specify a TAG so that the pending/ongoing requests can be cancelled.
     *
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

3、异步的JSON、String请求
Volley提供了以下的实用工具类进行异步HTTP请求:
JsonObjectRequest — To send and receive JSON Object from the Server
JsonArrayRequest — To receive JSON Array from the Server
StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)
JsonObjectRequest
这个类可以用来发送和接收JSON对象。这个类的一个重载构造函数允许设置适当的请求方法(DELETE,GET,POST和PUT)。如果您正在使用一个RESTful服务端,可以使用这个类。下面的示例显示如何使GET和POST请求。
GET请求:

final String URL = "/volley/resource/12";
// pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(URL, null,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    VolleyLog.v("Response:%n %s", response.toString(4));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
    }
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

POST请求:

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token","AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    VolleyLog.v("Response:%n %s", response.toString(4));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
    }
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

JsonArrayRequest
这个类可以用来接受 JSON Arrary,不支持JSON Object。这个类现在只支持 HTTP GET。由于支持GET,你可以在URL的后面加上请求参数。类的构造函数不支持请求参数。

final String URL = "/volley/resource/all?count=20";
JsonArrayRequest req = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray response) {
        try {
            VolleyLog.v("Response:%n %s", response.toString(4));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
    }
});
// add the request object to the queue to be executed
ApplicationController.getInstance(). addToRequestQueue(req);

StringRequest
这个类可以用来从服务器获取String,如果想自己解析请求响应可以使用这个类,例如返回xml数据。它还可以使用重载的构造函数定制请求。

final String URL = "/volley/resource/recent.xml";
StringRequest req = new StringRequest(URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        VolleyLog.v("Response:%n %s", response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
    }
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

4、取消请求
Volley提供了强大的API取消未处理或正在处理的请求。取消请求最简单的方法是调用请求队列cancelAll(tag)的方法,前提是你在添加请求时设置了标记。这样就能使标签标记的请求挂起。
给请求设置标签:

request.setTag("My Tag");

使用ApplicationController添加使用了标签的请求到队列中:

ApplicationController.getInstance().addToRequestQueue(request, "My Tag");

取消所有指定标记的请求:

mRequestQueue.cancelAll("My Tag");

5、请求失败的重试次数,自定义请求超时时间
Volley中没有指定的方法来设置请求超时时间,可以设置RetryPolicy来变通实现。
DefaultRetryPolicy类有个initialTimeout参数,可以设置超时时间。要确保最大重试次数为1,以保证超时后不重新请求。

request.setRetryPolicy(new DefaultRetryPolicy(int initialTimeoutMs, int maxNumRetries, float backoffMultiplier));
request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, 1.0f));

initialTimeoutMs参数是设置超时时长,默认为2500,可以设置稍微长点;
maxNumRetries参数是设置最大重复请求次数,默认为1,可以设置为0;
backoffMultiplier参数为设置 “允许你指定一个退避乘数可以用来 实现<指数退避>来从RESTful服务器请求数据”,默认值为1,当取1时,即可以简单理解为 ” 每次超时请求时长都是 <前一次超时请求时长 *2> “,以此类推
如:      
    initialTimeoutMs为 5,maxNumRetries为 2,backoffMultiplier为 2   
则:
    第一次超时时长: 5 + (5 * 2) = 15;
    第二次超时时长: 15 +(15 * 2)= 45;

6、设置请求头(HTTP headers)
有时候需要给HTTP请求添加额外的头信息,一个常用的例子是添加 “Authorization”到HTTP 请求的头信息。Volley请求类提供了一个 getHeaers()的方法,重载这个方法可以自定义HTTP 的头信息。
添加头信息:

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // handle response
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // handle error
            }
        }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("CUSTOM_HEADER", "Yahoo");
                    headers.put("ANOTHER_CUSTOM_HEADER", "Google");
                    return headers;
                }
            };

7、错误处理
正如前面代码看到的,在创建一个请求时,需要添加一个错误监听onErrorResponse。如果请求发生异常,会返回一个VolleyError实例。
以下是Volley的异常列表:
AuthFailureError:如果在做一个HTTP的身份验证,可能会发生这个错误。
NetworkError:Socket关闭,服务器宕机,DNS错误都会产生这个错误。
NoConnectionError:和NetworkError类似,这个是客户端没有网络连接。
ParseError:在使用JsonObjectRequest或JsonArrayRequest时,如果接收到的JSON是畸形,会产生异常。
SERVERERROR:服务器的响应的一个错误,最有可能的4xx或5xx HTTP状态代码。
TimeoutError:Socket超时,服务器太忙或网络延迟会产生这个异常。默认情况下,Volley的超时时间为2.5秒。如果得到这个错误可以使用RetryPolicy。
对于不同异常做相应的提示,代码如下:

@Override
public void onErrorResponse(VolleyError volleyError) {
    if (volleyError instanceof ParseError) {// 解析错误
        Log.w(TAG, "解析错误");
    } else if (volleyError instanceof TimeoutError) {// 请求超时
        Log.w(TAG, "请求超时");
    } else if (volleyError instanceof NetworkError || volleyError instanceof NoConnectionError) {// 连接异常错误
        Log.w(TAG, "连接异常,请检查网络配置或服务器");
    } else if (volleyError instanceof ServerError) {// 服务器错误
        Log.w(TAG, "系统错误");
    } else {// 其他错误
    }
}

转自(有改动):https://www.cnblogs.com/spec-dog/p/3723322.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值