您的位置:首页 > 理论基础 > 计算机网络

Android网络编程五:(5)Volley功能介绍

2015-03-23 16:02 281 查看
转自:/article/1355125.html

Volley是Android开发者新的瑞士军刀,它提供了优美的框架,使得Android应用程序网络访问更容易和更快。Volley抽象实现了底层的HTTP Client库,让你不关注HTTP Client细节,专注于写出更加漂亮、干净的RESTful HTTP请求。另外,Volley请求会异步执行,不阻挡主线程。

Volley提供的功能

简单的讲,提供了如下主要的功能:

1、封装了的异步的RESTful 请求API;

2、一个优雅和稳健的请求队列;

3、一个可扩展的架构,它使开发人员能够实现自定义的请求和响应处理机制;

4、能够使用外部HTTP Client库;

5、缓存策略;

6、自定义的网络图像加载视图(NetworkImageView,ImageLoader等);

为什么使用异步HTTP请求?

Android中要求HTTP请求异步执行,如果在主线程执行HTTP请求,可能会抛出android.os.NetworkOnMainThreadException 异常。阻塞主线程有一些严重的后果,它阻碍UI渲染,用户体验不流畅,它可能会导致可怕的ANR(Application Not Responding)。要避免这些陷阱,作为一个开发者,应该始终确保HTTP请求是在一个不同的线程。

怎样使用Volley

这篇博客将会详细的介绍在应用程程中怎么使用volley,它将包括一下几方面:

1、安装和使用Volley库

2、使用请求队列

3、异步的JSON、String请求

4、取消请求

5、重试失败的请求,自定义请求超时

6、设置请求头(HTTP headers)

7、使用Cookies

8、错误处理

安装和使用Volley库

引入Volley非常简单,首先,从git库先克隆一个下来:

[plain] view plaincopyprint?

git clone https://android.googlesource.com/platform/frameworks/volley

然后编译为jar包,再把jar包放到自己的工程的libs目录。

使用请求队列

Volley的所有请求都放在一个队列,然后进行处理,这里是你如何将创建一个请求队列:

[java] view plaincopyprint?

RequestQueue mRequestQueue = Volley.newRequestQueue(this); // ‘this’ is Context

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

[java] view plaincopyprint?

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


}

异步的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请求:

[java] view plaincopyprint?

final String URL = “/volley/resource/12”;

// pass second argument as “null” for GET requests

JsonObjectRequest req = new JsonObjectRequest(URL, null,

new Response.Listener() {

@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请求:

[java] view plaincopyprint?

final String URL = “/volley/resource/12”;

// Post params to be sent to the server

HashMap
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐