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

转自:http://blog.csdn.net/xyz_lmn/article/details/12177005

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值