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

Volley网络框架

2016-02-17 22:02 253 查看
1.Volley概述:

Volley简介

Volley:齐射,并发
Volley是谷歌发布的android平台的网络通信库

Volley特点

通信更快,更简单
Get,Post网络请求及网络图像的高效率异步请求排序
网络请求的缓存
多级别取消请求
和Activity生命周期联动

Volley缺点

不适合数据的上传和下载

使用Volley的原因

功能上

高效的Get/Post方式的数据请求交互
网络图片加载和缓存

其他

谷歌官方推出
性能稳定和强劲

2.Volley的使用:

学习目标

Volley的get和post请求方式的使用

Get和Post请求接口数据的使用

根据不同的数据接口挑选合适的对象 1.StringRequest 2.JsonObjectRequest 3.JsonArrayRequest
回调的使用

Volley的网络请求队列的建立和取消队列请求

建立请求队列
取消某个请求

Volley与Activity声明周期的联动

特点

可以在Activity销毁的时候同时关闭请求

关键点

设置Tag标签,onStop()里执行取消请求

Volley的简单的二次回调封装

优势

全局使用一个方式,可控,可自定义定制需求

实践

1.建立全局队列

新建一个MyApplication类继承Application

在项目下的AndroidManifest中为application标签,添加一个name属性,值为MyApplication这个类

<application

android :allowBackup="true"

android :icon="@mipmap/ic_launcher"

android :label="@string/app_name"

android :name=".MyApplication "

android :supportsRtl="true"

android :theme="@style/AppTheme">

这样MyApplication这个对象的生命周期跟整个应用的生命周期就是一致的,用来存放一些全局数据。

代码

package com.xl.volleydemo;

import android.app.Application ;

import com.android.volley.RequestQueue ;

import com.android.volley.toolbox.Volley ;

/**

* Created by Administrator on 2/17/2016.

*/

public class MyApplication extends Application
{

public static RequestQueue queues;

@Override

public void onCreate()
{

super .onCreate();

queues = Volley. newRequestQueue(getApplicationContext()) ;//获得全局请求队列

}

public static RequestQueue getHttpQueues(){

return queues;//全局请求队列

}

}

2.使用get和post方式来请求数据

这边我在MaInActivity中写了两个方法分别用来执行get和post请求数据

操作如下,

1.新建一个Request对象

2.为Request对象设置标签(方便从队列中找到该对象)

3.将其添加到全局队列中。

String url = "http://apis.juhe.cn/mobile/get?phone=18850290882&key=759e239954bd5966ba8cbe8fd91675f9" ;//访问的接口

StringRequest request = new StringRequest(Request.Method.GET, url,

new Response.Listener<String>() { //实例化request对象

@Override

public void onResponse(String
response) {

//数据请求成功

Toast. makeText(getApplicationContext() ,response, Toast.LENGTH_LONG).show() ;

}

},new Response.ErrorListener(){

@Override

public void onErrorResponse(VolleyError
error) {

//数据请求失败

Toast. makeText(getApplicationContext() ,error.toString(), Toast.LENGTH_LONG).show() ;

}

});

request.setTag( "StringGet"); //添加Tag标记方便在全局队列中寻找

MyApplication.getHttpQueues().add(request);//添加到全局队列中

这样就可以用Get方式获取网络数据了。

下面来谈一谈 StringRequest,JsonRequeqst,JsonArrayRequest

1.StringRequest有两个构造

构造一:

/**

* Creates a new request with the given method.

*

* @param method the
request {@link Method} to use

* @param url URL
to fetch the string at

* @param listener Listener
to receive the String response

* @param errorListener Error
listener, or null to ignore errors

*/

public StringRequest(int method , String
url, Listener<String> listener ,

ErrorListener errorListener) {

super (method, url , errorListener);

mListener = listener;

}

构造二:

/**

* Creates a new GET request.

*

* @param url URL
to fetch the string at

* @param listener Listener
to receive the String response

* @param errorListener Error
listener, or null to ignore errors

*/

public StringRequest(String url , Listener<String>
listener, ErrorListener errorListener) {

this (Method.GET, url, listener , errorListener);

}

可以看出构造一的四个参数分别是,请求方式,访问的接口,访问回调,失败回调

构造二的没有请求方式的参数。默认为get请求

2.JsonObjectRequest有五个构造

/**

* Creates a new request.

* @param method the
HTTP method to use

* @param url URL
to fetch the JSON from

* @param requestBody A
{@link String} to post with the request. Null is allowed and

* indicates no parameters will be posted along with request.

* @param listener Listener
to receive the JSON response

* @param errorListener Error
listener, or null to ignore errors.

*/

public JsonObjectRequest(int method , String
url, String requestBody,

Listener<JSONObject> listener , ErrorListener
errorListener) {

super (method, url , requestBody, listener,

errorListener) ;

}

/**

* Creates a new request.

* @param url URL
to fetch the JSON from

* @param listener Listener
to receive the JSON response

* @param errorListener Error
listener, or null to ignore errors.

*/

public JsonObjectRequest(String url , Listener<JSONObject>
listener, ErrorListener errorListener) {

super (Method.GET, url,
null, listener , errorListener);

}

/**

* Creates a new request.

* @param method the
HTTP method to use

* @param url URL
to fetch the JSON from

* @param listener Listener
to receive the JSON response

* @param errorListener Error
listener, or null to ignore errors.

*/

public JsonObjectRequest(int method , String
url, Listener<JSONObject> listener , ErrorListener
errorListener) {

super (method, url ,
null, listener, errorListener);

}

/**

* Creates a new request.

* @param method the
HTTP method to use

* @param url URL
to fetch the JSON from

* @param jsonRequest A
{@link JSONObject} to post with the request. Null is allowed and

* indicates no parameters will be posted along with request.

* @param listener Listener
to receive the JSON response

* @param errorListener Error
listener, or null to ignore errors.

*/

public JsonObjectRequest(int method , String
url, JSONObject jsonRequest,

Listener<JSONObject> listener , ErrorListener
errorListener) {

super (method, url , (jsonRequest
== null ) ? null :
jsonRequest.toString() , listener,

errorListener) ;

}

/**

* Constructor which defaults to <code>GET </code> if <code>jsonRequest </code> is

* <code> null</code>, <code> POST</code> otherwise.

*

* @see #JsonObjectRequest(int,
String, JSONObject, Listener, ErrorListener)

*/

public JsonObjectRequest(String url , JSONObject
jsonRequest, Listener<JSONObject> listener ,

ErrorListener errorListener) {

this (jsonRequest == null ?
Method. GET : Method.POST, url, jsonRequest ,

listener , errorListener);

}

五个构造参数也都差不多,有一个参数是放请求携带的数据,构造重载,参数可以为字符串,也可以传输Json对象。

还有一个是JsonArrayRequest,一般都是用前两个所以JsonArrayRequest不做测试。

下面的代码把前两种数据get和post获取的代码写出来了。

如下:

private void volley_Post()
{

String url= "http://apis.juhe.cn/mobile/get?" ;

// StringRequest request =new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {

// @Override

// public void onResponse(String response) {

// Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG).show();

// }

// }, new Response.ErrorListener() {

// @Override

// public void onErrorResponse(VolleyError error) {

// Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();

// }

// }){

// @Override

// protected Map<String, String> getParams() throws AuthFailureError {

// Map<String,String> hashMap = new HashMap<String,String>();

// hashMap.put("phone","18850290882");

// hashMap.put("key","759e239954bd5966ba8cbe8fd91675f9");

// return hashMap;

// }

// };

// request.setTag("StringPost");//方便在全局队列中寻找

// MyApplication.getHttpQueues().add(request);

HashMap<String ,String>
hashMap = new HashMap<String,String>() ;

hashMap.put("phone" ,"18850290882") ;

hashMap.put("key" ,"759e239954bd5966ba8cbe8fd91675f9");

JSONObject jsonObject = new JSONObject(hashMap);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject ,
new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject
response) {

Toast.makeText(getApplicationContext(),response.toString() ,Toast.LENGTH_LONG).show() ;

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError
error) {

Toast.makeText(getApplicationContext(),error.toString() ,Toast.LENGTH_LONG).show() ;

}

});

jsonObjectRequest.setTag( "json"); //方便在全局队列中寻找

MyApplication. getHttpQueues().add(jsonObjectRequest) ;

}

private void volley_Get()
{

String url= "http://apis.juhe.cn/mobile/get?phone=18850290882&key=759e239954bd5966ba8cbe8fd91675f9" ;

// StringRequest request =new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

// @Override

// public void onResponse(String response) {

// //数据请求成功

// Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG).show();

// }

// },new Response.ErrorListener(){

//

//

// @Override

// public void onErrorResponse(VolleyError error) {

// //数据请求失败

// Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();

// }

// });

// request.setTag("StringGet");//方便在全局队列中寻找

// MyApplication.getHttpQueues().add(request);

JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url,"" ,new Response.Listener<JSONObject>()
{

@Override

public void onResponse(JSONObject
response) {

Toast.makeText(getApplicationContext(),response.toString() ,Toast.LENGTH_LONG).show() ;

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError
error) {

Toast.makeText(getApplicationContext(),error.toString() ,Toast.LENGTH_LONG).show() ;

}

});

jsonRequest.setTag( "json"); //方便在全局队列中寻找

MyApplication. getHttpQueues().add(jsonRequest) ;

}

3.Volley与Activity生命周期联动:

1.在Activity的onStop方法执行的时候把全局队列中的request对象取消掉,刚才设置的Tag标签派上用场。

@Override

protected void onStop()
{

super .onStop();

MyApplication. getHttpQueues().cancelAll( "json");

}

对Volley进行二次封装

(1)自定义Get和Post方法

(2)重新封装接口回调方法

package com.xl.volleydemo;

import android.content.Context ;

import com.android.volley.AuthFailureError ;

import com.android.volley.Request ;

import com.android.volley.Response ;

import com.android.volley.VolleyError ;

import com.android.volley.toolbox.StringRequest ;

import java.util.Map ;

/**

* Created by Administrator on 2/17/2016.

*/

public class VolleyRequest {

public static StringRequest stringRequest;

public static Context context;

public static void RequestGet (Context mContext,String
url ,String tag, VolleyInterface
vif)

{

MyApplication.getHttpQueues ().cancelAll(tag);

stringRequest = new StringRequest(Request.Method.GET, url, vif.loadingListener() ,vif.errorListener()) ;

stringRequest.setTag(tag) ;

MyApplication. getHttpQueues().add( stringRequest);

MyApplication. getHttpQueues().start() ;

}

public static void RequestPost(Context
mContext, String url,String
tag ,

final Map<String,String>
params , VolleyInterface vif)

{

MyApplication.getHttpQueues ().cancelAll(tag);

stringRequest = new StringRequest(Request.Method.POST, url, vif.loadingListener() ,vif.errorListener()){

@Override

protected Map<String, String> getParams() throws AuthFailureError
{

return params ;

}

};

stringRequest.setTag(tag) ;

MyApplication. getHttpQueues().add( stringRequest);

MyApplication. getHttpQueues().start() ;

}

}

请求成功和失败的监听接口

package com.xl.volleydemo;

import android.content.Context ;

import com.android.volley.Response ;

import com.android.volley.Response.ErrorListener ;

import com.android.volley.Response.Listener ;

import com.android.volley.VolleyError ;

/**

* Created by Administrator on 2/17/2016.

*/

public abstract class VolleyInterface {

public Context mContext;

public static Listener<String> mListener;

public static ErrorListener mErrorListener;

public VolleyInterface(Context context , Listener<String>
listener, ErrorListener errorListener) {

this .mContext =
context ;

this. mListener =
listener;

this. mErrorListener =
errorListener;

}

public Listener<String> loadingListener()
{

mListener = new Listener<String>()
{

@Override

public void onResponse(String
response) {

onMySuccess(response);

//弹出加载框

}

};

return mListener;

}

public ErrorListener errorListener()

{

mErrorListener = new ErrorListener()
{

@Override

public void onErrorResponse(VolleyError
error) {

onMyError(error);

//提示请求失败

}

};

return mErrorListener;

}

public abstract void onMySuccess(String
result);

public abstract void onMyError (VolleyError
error);

}

Activity中的实现

private void volley_Get()
{

String url = "http://apis.juhe.cn/mobile/get?phone=18850290882&key=759e239954bd5966ba8cbe8fd91675f9" ;

VolleyRequest. RequestGet( this, url, "StringGet",
new VolleyInterface( this,VolleyInterface.mListener, VolleyInterface.mErrorListener)
{

@Override

public void onMySuccess(String
result) {

Toast.makeText (getApplicationContext(),result ,Toast.LENGTH_LONG).show() ;

}

@Override

public void onMyError(VolleyError
error) {

Toast.makeText (getApplicationContext(),error.toString() ,Toast.LENGTH_LONG).show() ;

}

});

}

这样做的好处是可以在封装接口中用统一的方法来对成功和失败进行一定的操作。避免每一次都要执行一遍。

4.加载网络图片及监听

三种方式:

ImageRequest:直接request请求

ImageLoader:加载缓存图片

NetworkImageView:volley自带的图片框架,加载缓存图片

1.使用Imageview不缓存图片

private void loadimage()
{

String url = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png" ;

ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {

@Override

public void onResponse(Bitmap
response) {

iv_img .setImageBitmap(response) ;

}

}, 0, 0 , Bitmap.Config.RGB_565,
new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError
error) {

iv_img .setImageResource(R.mipmap. ic_launcher);

}

});

MyApplication. getHttpQueues().add(request) ;

}

2.使用imageview缓存图片需要对ImageCache接口进行实现

package com.xl.volleydemo;

import android.graphics.Bitmap ;

import android.util.LruCache ;

import com.android. volley.toolbox.ImageLoader.ImageCache ;

/**

* LruCache

* Created by Administrator on 2/17/2016.

*/

public class BitmapCache implements ImageCache
{

private LruCache<String,Bitmap> cache;

public int max = 10* 1024*1024 ;

public BitmapCache()

{

cache = new LruCache<String ,Bitmap>(max )

{

@Override

protected int sizeOf(String
key, Bitmap value) {

return value.getRowBytes()*value.getHeight() ;

}

};

}

@Override

public Bitmap getBitmap(String
url) {

return cache.get(url);

}

@Override

public void putBitmap(String
url, Bitmap bitmap) {

cache .put(url,bitmap) ;

}

}

Activity中的实现

private void cacheimage()
{

String url = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png" ;

ImageLoader imageLoader = new ImageLoader(MyApplication.getHttpQueues(),new BitmapCache()) ;

ImageListener listener = ImageLoader.getImageListener( iv_img2,R.mipmap. ic_launcher,R.mipmap. ic_launcher);

imageLoader.get(url ,listener);

}

3.NetworkImageView

private void netImageViewLoader()
{

String url = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png" ;

ImageLoader imageLoader = new ImageLoader(MyApplication.getHttpQueues(),new BitmapCache()) ;

networkImageView .setDefaultImageResId(R.mipmap. ic_launcher);

networkImageView .setErrorImageResId(R.mipmap. ic_launcher);

networkImageView .setImageUrl(url,imageLoader) ;

}

源码地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: