Android 网络框架Volley的使用

时间:2023-03-09 17:55:18
Android 网络框架Volley的使用

Android 网络框架Volley的使用

Volley简介

在平时的开发过程中,我们的应用几乎总是在和网络打交道, 在android下的网络编程一般都是基于Http协议的 ,常见的是HttpURLConnection和HttpClient 两个类。因为用的比较多,很容易写一些重复的代码,于是就出现了一些比较好的网络框架,像AsyncHttpClient 、Xutils,Universal-Image-Loader(网络图片加载框架)等。

Volley是Google在2013年I/O大会上退出的一款新的网络框架,它集成了AsyncHttpClient和Universal-Image-Loader的优点,在数据量不大但通信频繁的网络操作中,用Volley非常适合。对于下载还是使用Xutils比较好。

Volley jar包下载

鉴于国内上外网的难度,可以上github上下载,https://github.com/mcxiaoke/android-volley一个和官方保持同步的非官方包

在使用过程中,发现它是一个AndroidStudio的包,并没有所谓的jar包。

如何将所谓的AndroidStudio工程导出为jar:详见:http://www.cnblogs.com/BoBoMEe/p/4294267.html

将jar包导入到lib目录下,或者将Volley的/com(此框架中没有设计到UI方面,没有资源文件)文件夹复制到src即可、。

Volley 提供的功能

  • JSON,图像等的异步下载
  • 网络请求的排序(scheduling)
  • 网络请求的优先级处理
  • 缓存处理
  • 多级别取消请求
  • 和Activity和生命周期的联动(Activity结束时同时取消所有网络请求)

Volley使用

①.创建RequestQueue对象

②.创建Request对象

③.将Request对象加入RequestQueue

StringRequest

这个类可以用来从服务器获取String,下面是一个简单的GET请求

//创建requestQueue 对象
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
/**
* 创建stringRequest
* String url, 请求地址
* Listener<String> listener,成功的监听
* ErrorListener errorListener 失败的监听
*/
StringRequest stringRequest = new StringRequest("http://www.baidu.com",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("TAG", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
// 添加到requestQueue 对象中
requestQueue.add(stringRequest);
//开始分发
requestQueue.start();

添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

这段代码,就是将百度首页的HTML代码给请求了过来。requestQueue很明显是一个请求队列,里面缓存了所有的HTTP请求。因此我们在一个类中创建一个requestQueue对象即可。

RequestQueue初始化过程

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

在android2.3 之前使用HttpClient,2.3之后使用HttpURLConnection,在这里也有体现

newRequestQueue(Context context, HttpStack stack)中的部分源码:

if (Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();
} else {
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}