弄明白android 网络库之Volley(一)

1Volley是什么?

VolleyGoogle官方在2013 Android IO大会上推出的新网络通信框架,

一个使得android网络通信更加容易并且迅速的HTTP库。它并且可以通过开放的AOSP仓库进行使用。

它有以下特性:

1)自动调度网络请求;

2)支持多并发的网络连接;

3)磁盘和内存响应缓存使用标准HTTP缓存特性;

4)支持请求优先级;

5)取消请求API。你可以取消一个请求,或者你可以设定块或取消的请求范围;

6)易于定制,例如,重试和补偿;

7)强大的排序,便于正确填充UI的从网络获取而来的异步数据;

8)有调试和跟踪工具

 

它就是一个让你更快捷更高效进行网络通信的android网络工具库,它适用于小数据的交换。对于大文件或者流媒体,它是不适合的。而对于大文件的下载操作,请考虑用其他的库,比如DownloadManager。

 

Volley is notsuitable for large download or streaming operations, since Volley holds allresponses in memory during parsing. For large download operations, considerusing an alternative like DownloadManager.

 

如果你安装有git,那么可以通过下面命令来获得 Volley的源码:

git clonehttps://android.googlesource.com/platform/frameworks/volley

 

二、如何使用Volley?

1、使用Volley发送一个简单的请求:

Volley提供了一个方法来根据一个URL发起一个HTTP请求。只需要做以下5个步骤:

 

1)下载volley.jar包,并加入到android工程的libs中;

2)配置上网的权限;

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


3)通过Volley的静态方法新建一个请求队列对象RequestQueue,这里解释下什么是RequestQueue,从它的源码可以大概了解到它是拥有好几个queue成员变量的对象,其中包括缓存队列和网络队列,都是采用优先级阻塞队列。因此,我们可以理解它为一个用来处理我们所提出所有网络请求的队列。

/** The cache triage queue. */
privatefinalPriorityBlockingQueue<Request<?>> mCacheQueue =
newPriorityBlockingQueue<Request<?>>();
/** The queue of requests that are actually going out to the network. */
privatefinalPriorityBlockingQueue<Request<?>> mNetworkQueue =
newPriorityBlockingQueue<Request<?>>();
 

RequestQueue queue = Volley.newRequestQueue(this);

4)提供一个URLnew一个StringRequest 对象;所谓StringRequest对象,在它源码注释可知,它就一个是利用给定的URL作为一个String去检索响应内容的封装请求对象。

/**
* A canned request for retrieving the response body at a given URL as a String.
*/
publicclassStringRequestextendsRequest<String>{
privatefinalListener<String> mListener;
/**
* 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
*/
publicStringRequest(int method,String url,Listener<String> listener,
ErrorListener errorListener){
super(method, url, errorListener);
mListener= listener;
}
 

5)并把它加入到RequestQueue队列中。

queue.add(stringRequest);

官方所给出的提示DEMO如下:

final TextView mTextView = (TextView) findViewById(R.id.text);
...
 
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
 
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
         new Response.Listener() {
   @Override
   public void onResponse(String response) {
      // Display the first 500 characters of the response string.
      mTextView.setText("Response is: "+ response.substring(0,500));
   }
}, new Response.ErrorListener() {
   @Override
   public void onErrorResponse(VolleyError error) {
      mTextView.setText("That didn't work!");
   }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
 


2、使用JSON传递数据:JsonRequest,返回JSONObject或者JSONArray

两个步骤:

1)把你要提交给服务器的东西封装到一个JSONObject ,并新建一个 JsonObjectRequest,使用RequestManager.addRequest(JsonObjectRequest,this);

把请求提交到队列中去;

RequestManager.addRequest(new JsonObjectRequest(Method.GET, VolleyApi.JSON_TEST, null,
responseListener(), errorListener()),this);

2)写一个responseListener实例来接收处理服务器返回的信息;

privateResponse.Listener<JSONObject> responseListener() {
return new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mTvResult.setText(response.toString());
}
};
}
 

执行以上代码就可以发送一个JSON请求.

那么 JsonObjectRequest是什么呢?顾名思义,JSON对象请求。

    public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
            Listener<JSONObject> listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                    errorListener);
    }

传入参数有5

method

HTTP定义的与服务器交互的方法,这里有定义了7个方法

String url

客户端要访问服务器的地址

JSONObject jsonRequest

客户端访问时要提交的数据,以JSON的形式

Listener<JSONObject> listener

服务器返回时的侦听接口,回调这个接口处理返回的JSONObject结果

ErrorListener errorListener

错误接口,回调使用

 从Method的源码可以看到,这里就是HTTP的通信方法,如果不太清楚下面几个方法的用处:请看

HTTP方法详解


    public interface Method {
        int DEPRECATED_GET_OR_POST = -1;
        int GET = 0;
        int POST = 1;
        int PUT = 2;
        int DELETE = 3;
        int HEAD = 4;
        int OPTIONS = 5;
        int TRACE = 6;
        int PATCH = 7;
    }

 而对于 两个listener,分别是接收服务器返回信息与错误信息的处理。应用的是Android回调机制

 /** Callback interface for delivering parsed responses. */
    public interface Listener<T> {
        /** Called when a response is received. */
        public void onResponse(T response);
    }
 
    /** Callback interface for delivering error responses. */
    public interface ErrorListener {
        /**
         * Callback method that an error has been occurred with the
         * provided error code and optional user-readable message.
         */
        public void onErrorResponse(VolleyError error);
    }

最后,上传一个应用Volley的Demo,里面简单演示了volley网络通信的过程,并且我加入了Volley的实现源码,可以对整个实现过程多加研究了解,从而懂得更多。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值