Android Volley

先提供下载地址:git clone https://android.googlesource.com/platform/frameworks/volley 

或 : https://github.com/mcxiaoke/android-volley

Volley的架构设计:

  Volley使用了线程池来作为基础结构,主要分为主线程,cache线程和network线程。
主线程和cache线程都只有一个,而NetworkDispatcher线程可以有多个,这样能解决比并行问题。

其提供的功能:

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

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

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

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

5、缓存策略;

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

使用三步骤:

(1)创建RequestQueue队列;

1 private RequestQueue mRequestQueue = null;
3 ....
4 //this代表当前的上下文
5 mRequestQueue = Volley.newRequestQueue(this);

(2)创建Request对象,并加入队列中;(3)处理回调事件。

默认提供两种数据请求类型,一为StringRequest,一为JsonRequest

JsonRequest又分:

  JsonArrayRequest(onResponse返回的JSONArray)

    这个类现在只支持 HTTP GET,由于支持GET,你可以在URL的后面加上请求参数。类的构造函数不支持请求参数。

  JsonObjectRequest(onResponse返回的JSONObject)

  1. StringRequest

    StringRequest的默认请求方式为GET.

 1 String url = "http://127.0.0.1:8080";
 2 StringRequest request = new StringRequest(url, new Response.Listener<String>()
 3         {
 4             @Override
 5             public void onResponse(String response)//success callbacks
 6             {
 7                 //handle it
 8             }
10         }, new Response.ErrorListener()//error callbacks
11         {
12             @Override
13             public void onErrorResponse(VolleyError error)
14             {
15                 error.printStackTrace();
16             }
17         });
18         //add request to queue...
19         mRequestQueue.add(request);

  2. JsonRequest

    JsonObject是android内置的org.json库,而不是Gson。

下面例子中:如果jsonRequest实例为null则是get请求,否则是post请求,如果jsonrequest不为null,volley会将jsonObject对象转化为json字符串原封不动的发给服务器,并不会转成k-v对,因为volley不知道应该如何转化。

Map<String,String> params = new HashMap<String,String>();
params.put("studentName", "student");
params.put("studentClass", "student");
JSONObject jsonRequest = new JSONObject(params);
String url = "http://127.0.0.1:8080/demo_volley/JsonTest";
JsonObjectRequest request = new JsonObjectRequest(url, jsonRequest, new Response.Listener<JSONObject>()
        {
            @Override
            public void onResponse(JSONObject response)
            {
                 //handle it
            }
            
        },new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                error.printStackTrace();
            }
        });
        mRequestQueue.add(request);

  3. ImageRequest

    ImageRequest可以控制图片的宽高、照片品质。如果宽高比原始宽高小的话,将会进行压缩。//参数如输入:0 0 代表不压缩。

 1 private void getImage(final ImageView imageView, String url) {
 2         ImageRequest imgRequest = new ImageRequest(url, 
 3                 new Response.Listener<Bitmap>() {
 4                     @Override
 5                     public void onResponse(Bitmap bitmap) {//下载成功后
 6                         imageView.setImageBitmap(bitmap);
 7                     }
 8                 }, 
 9                 imageView.getWidth(), imageView.getHeight(), Bitmap.Config.ARGB_8888, 
10                 new Response.ErrorListener(){
11                     @Override
12                     public void onErrorResponse(VolleyError error) { //下载出错
13                         //显示默认图片
14                     }
15                 });
16         mRequestQueue.add(imgRequest);
17     }

添加请求头:

  重写例如:JsonObjectRequest类中的getHeaders方法。

1 @Override  
2 public Map<String, String> getHeaders() throws AuthFailureError {  
3     HashMap<String, String> headers = new HashMap<String, String>();  
4     headers.put("CUSTOM_HEADER", "student");  
5     headers.put("ANOTHER_CUSTOM_HEADER", "Google");  
6     return headers;  
7 }  

添加Post参数:

  添加Post请求参数可以重写Request的GetParams方法,另需 修改请求参数为POST。

 1 String url = "http://127.0.0.1:8080/demo_volley/JsonTest";
 2 StringRequest request = new StringRequest(Method.POST,url,listener, errorListener)
 3         {
 4             //post请求需要复写getParams方法
 5             @Override
 6             protected Map<String, String> getParams() throws AuthFailureError
 7             {
 8                 Map<String,String> map = new HashMap<String,String>();
 9                 map.put("studentName","student");
10                 map.put("studentClass", "student");
11                 return map;
12             }            
13         };

使用Cookies:

  Volley中没有直接的API来设置cookies,如果需要,则需要修改Volley源码。修改ApplicationController类下的getRequestQueue()方法:

 1 // HttpClient 实例
 2 private DefaultHttpClient mHttpClient;  
 3 public RequestQueue getRequestQueue() {
 6     if (mRequestQueue == null) {  
 7         // 初始化HttpClient实例.   
 8         // 需要用其实例访问cookie  
 9         mHttpClient = new DefaultHttpClient();  
10         // create the request queue  
11         mRequestQueue = Volley.newRequestQueue(this, new HttpClientStack(mHttpClient));  
12     }  
13     return mRequestQueue;  
14 }  

添加setCookie方法:

 1 /** 
 2  * 设置cookie 
 3  */  
 4 public void setCookie() {  
 5     CookieStore mCookieStore = mHttpClient.getCookieStore();  
 6     // 创建cookie  
 7     mCookieStore.addCookie(new BasicClientCookie2("cookie", "student"));  
 8 }  
 9 
11 // 使用:在添加请求到列表前添加cookie
12 setCookie(); 

Volley的异常列表:

AuthFailureError:如果在做一个HTTP的身份验证,可能会发生这个错误。

NetworkError:Socket关闭,服务器宕机,DNS错误都会产生这个错误。

NoConnectionError:和NetworkError类似,这个是客户端没有网络连接。

ParseError:在使用JsonObjectRequest或JsonArrayRequest时,如果接收到的JSON是畸形,会产生异常。

SERVERERROR:服务器的响应的一个错误,最有可能的4xx或5xx HTTP状态代码。

TimeoutError:Socket超时,服务器太忙或网络延迟会产生这个异常。默认情况下,Volley的超时时间为2.5秒。如果得到这个错误可以使用RetryPolicy。

参考文档:

http://www.chengxuyuans.com/Android/90526.html

http://blog.csdn.net/jjwwmlp456/article/details/41247223

原文地址:https://www.cnblogs.com/CharlesGrant/p/4908090.html