Android Volley框架详解

来源:互联网 发布:手把手教你单片机 pdf 编辑:程序博客网 时间:2022/08/11 15:54

注:文章出自http://blog.csdn.net/guolin_blog/article/details/17482095,有兴趣可以先去阅读。

Volley简介

对于Android系统网络通信,我们知道目前用的最普遍的就是HttpClient和HttpURLConnection,但是HttpURLConnection和HttpClient的用法还是稍微有些复杂的,需要我们去封装代码,减少冗余度。Google开发团队也看到了这个问题,所以在2013年Google I/O大会上推出了一个新的网络通信框架——Volley,Volley集成了AsyncHttpClient框架和Universal-Image-Loader为一体,在性能方面也进行了大幅度的调整,非常适合去进行数据量不大,但通信频繁的网络操作。

Volley下载

①.如果你的电脑安装过git,请使用如下命令

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

②.如果你的电脑没安装git,请到此地址下载

Volley使用流程

 ①.创建RequestQueue对象
 ②.创建Request对象
 ③.将Request对象加入RequestQueue

Volley自带请求

 1.StringRequest ---请求字符串

private void requestStringData() {RequestQueue mRequestQueue = Volley.newRequestQueue(this);// 指定请求方式,携带请求参数StringRequest mRequest = new StringRequest(Method.POST, "http://www.baidu.com", new Response.Listener<String>() {@Overridepublic void onResponse(String response) {Log.d(TAG, response);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.d(TAG, error.getMessage(), error);}}) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String, String> mParams = new HashMap<String, String>();mParams.put("params1", "value1");mParams.put("params2", "value2");return mParams;}};mRequestQueue.add(mRequest);}

除了我们上面讲到的Volley处理流程之外,如果要添加请求参数的话,我们可以去重写它的getParams方法。

2.JsonRequest ---请求Json对象

private void requestJosnObjectData() {RequestQueue mRequestQueue = Volley.newRequestQueue(this);JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://m.weather.com.cn/data/101010100.html", null, new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.d(TAG, response.toString());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.e(TAG, error.getMessage(), error);}});mRequestQueue.add(jsonObjectRequest);}

3.JsonArrayRequest ---请求json数组

 略

4.ImageRequest ---请求图片(1)

private void showImage() {RequestQueue mRequestQueue = Volley.newRequestQueue(this);ImageRequest mImageRequest = new ImageRequest("http://www.baidu.com/img/bdlogo.png", new Response.Listener<Bitmap>() {@Overridepublic void onResponse(Bitmap response) {imageView.setImageBitmap(response);}}, 0, 0, Config.RGB_565, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.i(TAG, error.getMessage(), error);}});mRequestQueue.add(mImageRequest);}

5.ImageLoader ---请求图片(2)

private void showImage2() {networkImageView.setVisibility(View.GONE);// 1. 创建一个RequestQueue对象。RequestQueue mRequestQueue = Volley.newRequestQueue(this);// 2. 创建一个ImageLoader对象。ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new BitmapCache());// 3. 获取一个ImageListener对象。ImageListener imageListener = ImageLoader.getImageListener(imageView, R.drawable.image_default, R.drawable.image_error);// 4. 调用ImageLoader的get()方法加载网络上的图片。//mImageLoader.get("http://www.baidu.com/img/bdlogo.png", imageListener);mImageLoader.get("http://www.baidu.com/img/bdlogo.png", imageListener, 200, 200);}

6.NetworkImageView ---请求图片(3)

    <com.android.volley.toolbox.NetworkImageView        android:id="@+id/iv_network"        android:layout_width="200dp"        android:layout_height="200dp" >    </com.android.volley.toolbox.NetworkImageView>
private void showImage3() {imageView.setVisibility(View.GONE);//1. 创建一个RequestQueue对象。RequestQueue mRequestQueue = Volley.newRequestQueue(this);//2. 创建一个ImageLoader对象。ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new BitmapCache());//3. 在布局文件中添加一个NetworkImageView控件。//4. 在代码中获取该控件的实例。//5. 设置要加载的图片地址。networkImageView.setDefaultImageResId(R.drawable.image_default);networkImageView.setErrorImageResId(R.drawable.image_error);networkImageView.setImageUrl("http://www.baidu.com/img/bdlogo.png", mImageLoader);}

指定自己的Volley请求(XmlRequest 

public class XMLRequest extends Request<XmlPullParser> {private final Listener<XmlPullParser> mListener;public XMLRequest(int method, String url, Listener<XmlPullParser> listener, ErrorListener errorListener) {super(method, url, errorListener);mListener = listener;}public XMLRequest(String url, Listener<XmlPullParser> listener, ErrorListener errorListener) {this(Method.GET, url, listener, errorListener);}@Overrideprotected Response<XmlPullParser> parseNetworkResponse(NetworkResponse response) {try {String xmlString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));XmlPullParser xmlPullParser = Xml.newPullParser();xmlPullParser.setInput(new StringReader(xmlString));return Response.success(xmlPullParser, HttpHeaderParser.parseCacheHeaders(response));} catch (UnsupportedEncodingException e) {return Response.error(new ParseError(e));} catch (XmlPullParserException e) {return Response.error(new ParseError(e));}}@Overrideprotected void deliverResponse(XmlPullParser response) {mListener.onResponse(response);}}

private void requestXml() {RequestQueue mRequestQueue = Volley.newRequestQueue(this);XMLRequest xmlRequest = new XMLRequest("http://flash.weather.com.cn/wmaps/xml/china.xml", new Response.Listener<XmlPullParser>() {@Overridepublic void onResponse(XmlPullParser response) {XmlParser(response);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {// TODO Auto-generated method stub}});mRequestQueue.add(xmlRequest);}

指定自己Request(GsonRequest 

注:需要导入gson.jar

public class GsonRequest<T> extends Request<T> {private final Listener<T> mListener;private Gson mGson;private Class<T> mClass;public GsonRequest(int method, String url, Class<T> clazz, Listener<T> listener, ErrorListener errorListener) {super(method, url, errorListener);mGson = new Gson();mClass = clazz;mListener = listener;}public GsonRequest(String url, Class<T> clazz, Listener<T> listener, ErrorListener errorListener) {this(Method.GET, url, clazz, listener, errorListener);}@Overrideprotected Response<T> parseNetworkResponse(NetworkResponse response) {try {String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));return Response.success(mGson.fromJson(jsonString, mClass), HttpHeaderParser.parseCacheHeaders(response));} catch (UnsupportedEncodingException e) {return Response.error(new ParseError(e));}}@Overrideprotected void deliverResponse(T response) {mListener.onResponse(response);}}
private void requestGson() {RequestQueue mRequestQueue = Volley.newRequestQueue(this);GsonRequest<Weather> gsonRequest = new GsonRequest<Weather>("http://www.weather.com.cn/data/sk/101010100.html", Weather.class, new Response.Listener<Weather>() {@Overridepublic void onResponse(Weather weather) {WeatherInfo weatherInfo = weather.getWeatherinfo();Log.d(TAG, "city is " + weatherInfo.getCity());Log.d(TAG, "temp is " + weatherInfo.getTemp());Log.d(TAG, "time is " + weatherInfo.getTime());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.e("TAG", error.getMessage(), error);}});mRequestQueue.add(gsonRequest);}

框架运行机制


源代码总结:

1. RequestQueue requestQueue = Volley.newRequestQueue(this);

 ①.stack == null,判断这个版本9,确定使用HttpURLConnection还是HttpClient

 ②.根据stack创建NetWork对象

 ③.创建RequestQueue,并start<创建一个缓存线程CacheDispatcher和四个网络线程NetworkDispatcher>

 2. requestQueue.add(request);

 ①.判断是否可以缓存,如果可以,加入缓存队列,否则,加入网络请求队列。request.setShouldCache(false);
 ②.缓存线程会一直在后台运行,不断的取出响应结果,是否为null,是否过期,两者不成立则Request.parseNetworkResponse()
 ③.网络请求线程也是在不断的运行的,会调用Network.performRequest()去发送请求,将请求结果封装成NetworkResponse对象返回
 ④.调用Request.parseNetworkResponse解析NetworkResponse
 ⑤.调用ExecutorDelivery.postResponse()回调解析出的数据
 ⑥.调用Request.deliverResponse()方法
 ⑦.最后我们再在这个方法中将响应的数据回调到Response.Listener的onResponse()方法

Volley1源码下载(StringRequest,JsonRequest,JsonArrayRequest)

Volley2源码下载(ImageRequest,ImageLoader,NetWorkImageView)

Volley3源码下载(XmlRequest,GsonRequest)

Volley4源码下载(运行机制)

0 0
原创粉丝点击