Volley是一个由Google推出的网络通信库,比较适合进行数据量不大,但通信频繁的网络操作!!!
首先在使用Volley网络通信之前,要在在AndroidManifest.xml 文件中添加对网络权限的声明:
<uses-permission android:name="android.permission.INTERNET"/>来看一下Volley类的使用流程:
1.创建继承Request的类的对象
2.创建RequestQueue对象
3.将第1步创建的Request对象添加到第2步创建的RequestQueue对象中。
提示:RequestQueue是一个是一个请求队列对象,可以缓存所有的http网络请求,并发送请求,所以不必为每次的http请求都创建一个RequestQueue对象,这样会造成资源的浪费,习惯上可以使用单例模式创建一个RequestQueue对象。
1.创建继承Request的类的对象首先在Volley中网络请求的基类是Request抽象类,所有的网络请求都要继承这个类,在这个Request抽象类中,有几个比较常用的参数和方法:
public interface Method { int DEPRECATED_GET_OR_POST = -1; int GET = 0; int POST = 1; int PUT = 2; int DELETE = 3; } 这个Method interface接口包含了一些不同网络请求的方式。/** * Set a tag on this request. Can be used to cancel all requests with this * tag by {@link RequestQueue#cancelAll(Object)}. */ public void setTag(Object tag) { mTag = tag; } /** * Returns this request's tag. * @see com.android.volley.Request#setTag(Object) */ public Object getTag() { return mTag; } 通过setTag()和getTag()方法可以为网络请求Request设置和获取标签,通过标签可以取消网络请求parseNetworkResponse()deliverResponse() 以上两个方法比较重要,是Request抽象类中的两个抽象方法,需要继承Request抽象类的子类去实现这两个方法,其中parseNetworkResponse()方法的作用是对返回的数据进行解析和格式转换,把获得的数据转换成成我们客户端所需要的数据类型,而deliverResponse()方法的作用是网络请求成功之后进行方法的回调。我们可以继承Request这个抽象类,构造出适合自身情况的网络请求的子类,并创建网络请求的对象,这样的话使用Volley框架的第一步也就完成了。
2.创建RequestQueue对象
一般来说,创建RequestQueue对象的方式有两种,一种是可以直接调用Volley的newRequestQueue()方法创建,另一种是根据自身的情况去自定义创建,不过核心的内容应该是一样的,我就以Volley的newRequestQueue()方法为例,简单的描述一下。
在描述之前,我先介绍几个涉及到的类,首先就是
HttpStack类:用于处理Http请求,并返回请求的结果,目前Volley中HttpStack有两个子类,一个是基于HttpURLConnection的HurlStack和基于HttpClient的HttpClientStack。
ResponseDelivery:请求结果传递的类
NetWork:网络类,代表了一个可执行的网络请求,它的实现类是BasicNetwork。
NetworkDispatcher:用于调度走网络的请求,启动后会不断的从网络请求的队列中取出请求处理,队列为空时则等待,请求结束后将结果传递给ResponseDelivery去执行后续处理。
CacheDispatcher:用于调度走缓存的请求,启动后会不断的从缓存请求队列中取出请求处理,队列为空则等待,请求结束后将结果传递给ResponseDelivery去执行后续处理。
Cache:缓存请求结果,CacheDispatcher会从Cache中获取缓存结果。
public static RequestQueue newRequestQueue(Context context, HttpStack stack) { File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); String userAgent = "volley/0"; try { String packageName = context.getPackageName(); PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); userAgent = packageName + "/" + info.versionCode; } catch (NameNotFoundException e) { } if (stack == null) { if (Build.VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } } Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start(); return queue; } 从以上newRequestQueue()的代码中可以看出,在构建RequestQueue对象时,首先要构造一个构造缓存的File对象cacheDir(为了使解析代码更加清楚一点,我就用以上代码中定义的的变量名),之后需要构造一个HttpStack的对象,在上述代码做了判断,当版本大于9的时候会构建一个HrulStack的对象,否则的话会构建一个HttpClientStack的对象,稍微了解了一下,应该是在版本小于9的情况下,使用HurlStack的对象的话会出现一些不太好解决的bug。之后就会利用构造的HttpStack的对象stack,构造一个NetWork的对象,NetWork的实现类是BasicNetwork,然后通过File的对象cacheDir构造一个DiskBasedCache磁盘缓存的对象,通过这个DiskBasedCache的对象和Network对象,构造一个RequestQueue对象queue,并调用queue的start()方法,这个的话,一个RequestQueue对象就构造完成了。我们去了解一下RequestQueue的start()方法
public void start() { stop(); // Make sure any currently running dispatchers are stopped. // Create the cache dispatcher and start it. mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery); mCacheDispatcher.start(); // Create network dispatchers (and corresponding threads) up to the pool size. for (int i = 0; i < mDispatchers.length; i++) { NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery); mDispatchers[i] = networkDispatcher; networkDispatcher.start(); } } 我们可以看到在start()方法中,首先会调用stop()方法去停止之前已经开启的线程,然后去构造一个CacheDispatcher线程的对象,同时,利用for循环构造n个NetworkDispatcher线程的对象,默认是4个,也就是构造一个RequestQueue对象之后,会默认开启五个线程。3.将第1步创建的Request对象添加到第2步创建的RequestQueue对象中。
添加的方式也是很简单,通过RequestQueue的add()方法就可以把Request的对象添加到队列中去。
public <T> Request<T> add(Request<T> request) { // Tag the request as belonging to this queue and add it to the set of current requests. request.setRequestQueue(this); synchronized (mCurrentRequests) { mCurrentRequests.add(request); } // Process requests in the order they are added. request.setSequence(getSequenceNumber()); request.addMarker("add-to-queue"); // If the request is uncacheable, skip the cache queue and go straight to the network. if (!request.shouldCache()) { mNetworkQueue.add(request); return request; } // Insert request into stage if there's already a request with the same cache key in flight. synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); if (mWaitingRequests.containsKey(cacheKey)) { // There is already a request in flight. Queue up. Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey); if (stagedRequests == null) { stagedRequests = new LinkedList<Request<?>>(); } stagedRequests.add(request); mWaitingRequests.put(cacheKey, stagedRequests); if (VolleyLog.DEBUG) { VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey); } } else { // Insert 'null' queue for this cacheKey, indicating there is now a request in // flight. mWaitingRequests.put(cacheKey, null); mCacheQueue.add(request); } return request; } } 以上是add()方法的源码,首先会把网络请求的对象添加到mCurrentRequests当前请求的集合中去,然后通过request.shouleCache()方法判断该请求能否被缓存,不能被缓存的话就把该请求添加到网络请求对应的队列中去,默认都是可以被缓存的,否则的话就执行以下操作,这里涉及到一个mWaitingRequests,它是一个HashMap的对象,而这个集合中,每一个key对应的value是一个Queue队列,mWaitingRequests是一个等待请求的集合,如果一个请求正在被处理并且可以被缓存的话,后续相同url的请求都会根据该请求的key,放到mWaitingRequests中对象的value上,也就是对应的Queue中去,这样的话就保证了相同url的请求不会重复执行,当有相同url的请求时,下一次执行时,会从缓存中获取结果(具体原因,稍后就会提到),当请求可以被缓存的时候,就通过getCacheKey()方法去获取该请求对应的key,如果在mWaitingRequests中包含对应的key的话,就把该请求添加到该key对应的Queue中去,否则的话就把请求添加到走缓存调度的线程对象的队列中去,也就是mCacheQueue。这样的话就把网络请求添加到队列中去了。
当把请求添加到队列中去之后,就应该去执行这个请求了,执行的方式也是有两种,一种是在CacheDispatcher线程中去执行, 一种是在NetworkDispatcher线程中执行。
在NetworkDispatcher线程的run()方法中
public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { long startTimeMs = SystemClock.elapsedRealtime(); Request<?> request; try { // Take a request from the queue. request = mQueue.take(); } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } try { request.addMarker("network-queue-take"); // If the request was cancelled already, do not perform the // network request. if (request.isCanceled()) { request.finish("network-discard-cancelled"); continue; } addTrafficStatsTag(request); // Perform the network request. NetworkResponse networkResponse = mNetwork.performRequest(request); request.addMarker("network-http-complete"); // If the server returned 304 AND we delivered a response already, // we're done -- don't deliver a second identical response. if (networkResponse.notModified && request.hasHadResponseDelivered()) { request.finish("not-modified"); continue; } // Parse the response here on the worker thread. Response<?> response = request.parseNetworkResponse(networkResponse); request.addMarker("network-parse-complete"); // Write to cache if applicable. // TODO: Only update cache metadata instead of entire record for 304s. if (request.shouldCache() && response.cacheEntry != null) { mCache.put(request.getCacheKey(), response.cacheEntry); request.addMarker("network-cache-written"); } // Post the response back. request.markDelivered(); mDelivery.postResponse(request, response); } catch (VolleyError volleyError) { volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); parseAndDeliverNetworkError(request, volleyError); } catch (Exception e) { VolleyLog.e(e, "Unhandled exception %s", e.toString()); VolleyError volleyError = new VolleyError(e); volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); mDelivery.postError(request, volleyError); } } }会有一个while(true){}的循环,里面涉及到的细节比较多,这里就不一一说明了,其中有一个mNetwork.performRequest(request),mNetwork是Network的对象,他的实现类是BasicNetwork,在BasicNetwork的performRequest()中public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = Collections.emptyMap(); try { // Gather headers. Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // Handle cache validation. if (statusCode == HttpStatus.SC_NOT_MODIFIED) { Entry entry = request.getCacheEntry(); if (entry == null) { return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart); } // A HTTP 304 response does not have all header fields. We // have to use the header fields from the cache entry plus // the new ones from the response. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 entry.responseHeaders.putAll(responseHeaders); return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart); } // Some responses such as 204s do not have content. We must check. if (httpResponse.getEntity() != null) { responseContents = entityToBytes(httpResponse.getEntity()); } else { // Add 0 byte response as a way of honestly representing a // no-content request. responseContents = new byte[0]; } // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, statusLine); if (statusCode < 200 || statusCode > 299) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new NoConnectionError(e); } VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart); if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else { // TODO: Only throw ServerError for 5xx status codes. throw new ServerError(networkResponse); } } else { throw new NetworkError(networkResponse); } } } }我们可以看到会有一个mHttpStack.performRequest(request,headers),mHttpStack就是HttpStack的对象,用于处理网络请求的,并把返回的HttpResponse的对象经过一些操作最后封装成一个NetworkResponse的对象,在NetworkDispatcher的run()方法中获得return的NetworkResponse对象之后,就会调用request.parseNetworkResponse(networkResponse),对获取的数据进行解析,parseNetworkResponse()是个抽象方法,子类自己去实现。调用完这个方法之后,通过ResponseDelivery的对象mDelivery.postResponse()去把解析出的结果传递给一个Executor去处理,ResponseDelivery的实现类是ExecutorDelivery。public void postResponse(Request<?> request, Response<?> response, Runnable runnable) { request.markDelivered(); request.addMarker("post-response"); mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable)); }在ExecutorDelivery的postResponse()的postResponse()中,我们可以看到会把传递过来的参数封装成一个ResposeDeliveryRunnable的对象交由Executor去处理,mResponsePoster就是Executor的对象,在ResposeDeliveryRunnable的run()方法中我们可以看到public void run() { // If this request has canceled, finish it and don't deliver. if (mRequest.isCanceled()) { mRequest.finish("canceled-at-delivery"); return; } // Deliver a normal response or error, depending. if (mResponse.isSuccess()) { mRequest.deliverResponse(mResponse.result); } else { mRequest.deliverError(mResponse.error); } // If this is an intermediate response, add a marker, otherwise we're done // and the request can be finished. if (mResponse.intermediate) { mRequest.addMarker("intermediate-response"); } else { mRequest.finish("done"); } // If we have been provided a post-delivery runnable, run it. if (mRunnable != null) { mRunnable.run(); } }当请求执行成功之后,就回去调用mRequest.deliverResponse(mResponse.result)方法,deliverResponse()是Request中的第二个抽象方法,用来执行请求成功后的回调方法,之后就会调用mRequest.finish()方法来结束这个请求,以下是Request的finish()方法。void finish(final String tag) { if (mRequestQueue != null) { mRequestQueue.finish(this); } if (MarkerLog.ENABLED) { final long threadId = Thread.currentThread().getId(); if (Looper.myLooper() != Looper.getMainLooper()) { // If we finish marking off of the main thread, we need to // actually do it on the main thread to ensure correct ordering. Handler mainThread = new Handler(Looper.getMainLooper()); mainThread.post(new Runnable() { @Override public void run() { mEventLog.add(tag, threadId); mEventLog.finish(this.toString()); } }); return; } mEventLog.add(tag, threadId); mEventLog.finish(this.toString()); } }在Request的finish()中会调用RequestQueue的finish()方法。以下是RequestQueue的finish()方法。<T> void finish(Request<T> request) { // Remove from the set of requests currently being processed. synchronized (mCurrentRequests) { mCurrentRequests.remove(request); } synchronized (mFinishedListeners) { for (RequestFinishedListener<T> listener : mFinishedListeners) { listener.onRequestFinished(request); } } if (request.shouldCache()) { synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); Queue<Request<?>> waitingRequests = mWaitingRequests.remove(cacheKey); if (waitingRequests != null) { if (VolleyLog.DEBUG) { VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.", waitingRequests.size(), cacheKey); } // Process all queued up requests. They won't be considered as in flight, but // that's not a problem as the cache has been primed by 'request'. mCacheQueue.addAll(waitingRequests); } } } }在RequestQueue的finish()方法中,会调用mCurrentRequests.remove(request),先从当前请求的集合中去移除中该请求,如果该请求是可以被缓存的话,就获取该请求的key,把等待请求集合mWaitRequests中该key对应的value,也就是Queue去remove掉,然后把移除的Queue添加到缓存线程对应的队列中去,mCacheQueue.addAll(waitingRequests),这样的话,该Queue中的请求的结果就会从缓存中获取,避免了重复的网络请求。在CacheDispatcher()的run()方法中
public void run() { if (DEBUG) VolleyLog.v("start new dispatcher"); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // Make a blocking call to initialize the cache. mCache.initialize(); while (true) { try { // Get a request from the cache triage queue, blocking until // at least one is available. final Request<?> request = mCacheQueue.take(); request.addMarker("cache-queue-take"); // If the request has been canceled, don't bother dispatching it. if (request.isCanceled()) { request.finish("cache-discard-canceled"); continue; } // Attempt to retrieve this item from cache. Cache.Entry entry = mCache.get(request.getCacheKey()); if (entry == null) { request.addMarker("cache-miss"); // Cache miss; send off to the network dispatcher. mNetworkQueue.put(request); continue; } // If it is completely expired, just send it to the network. if (entry.isExpired()) { request.addMarker("cache-hit-expired"); request.setCacheEntry(entry); mNetworkQueue.put(request); continue; } // We have a cache hit; parse its data for delivery back to the request. request.addMarker("cache-hit"); Response<?> response = request.parseNetworkResponse( new NetworkResponse(entry.data, entry.responseHeaders)); request.addMarker("cache-hit-parsed"); if (!entry.refreshNeeded()) { // Completely unexpired cache hit. Just deliver the response. mDelivery.postResponse(request, response); } else { // Soft-expired cache hit. We can deliver the cached response, // but we need to also send the request to the network for // refreshing. request.addMarker("cache-hit-refresh-needed"); request.setCacheEntry(entry); // Mark the response as intermediate. response.intermediate = true; // Post the intermediate response back to the user and have // the delivery then forward the request along to the network. mDelivery.postResponse(request, response, new Runnable() { @Override public void run() { try { mNetworkQueue.put(request); } catch (InterruptedException e) { // Not much we can do about this. } } }); } } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } } }同样会有一个while(true){}的循环,首先会调用mCache.get(request.getCacheKey()),通过该请求的key尝试从缓存中获取缓存结果,如果缓存结果为空,就把该请求添加到网络线程对应的队列中去,如果缓存结果过期,同样把该请求添加到网络线程对应的队列中去,如果缓存结果不为空且没有过期的话,就去调用请求的parseNetworkResponse(),后续的步骤应该和NetworkDispatcher类似,就不再多说了。这就是一个完整的Volley请求的流程吧!!!
另外在RequestQueue中,还有cancelAll()方法,用于取消所有具有相同tag标签的网络请求,该代码如下
/** * Cancels all requests in this queue with the given tag. Tag must be non-null * and equality is by identity. */ public void cancelAll(final Object tag) { if (tag == null) { throw new IllegalArgumentException("Cannot cancelAll with a null tag"); } cancelAll(new RequestFilter() { @Override public boolean apply(Request<?> request) { return request.getTag() == tag; } }); }/** * Cancels all requests in this queue for which the given filter applies. * @param filter The filtering function to use */ public void cancelAll(RequestFilter filter) { synchronized (mCurrentRequests) { for (Request<?> request : mCurrentRequests) { if (filter.apply(request)) { request.cancel(); } } } }根据代码,我们可以看出,当我们以tag为参数调用cancelAll()方法的时候,Volley就会调用request.cancel()把所有匹配该tag的请求取消掉。以下是request.cancel()的源码
public void cancel() { mCanceled = true; }只有一句,把mCanceled参数设置为true,结合NetworkDispatcher以及CacheDispatcher两个线程的run()方法我们可以看到,在两个线程的run()中都会有if(request.isCanceled()){request.finish();continue;},当一个请求被取消的时候,就会调用请求的request.finish()方法去结束这个请求,并不去执行它,也就是说当我们调用cancellAll()取消一个请求之后,并不会立即去结束或者取消这个请求,相当于是做了一个标记,当在RequestQueue队列中执行到这个请求的时候,发现这个标志为true,即mCanceled=true,代表这个请求已经取消了,这个时候采取调用request.finish()去结束这个请求。
新闻热点
疑难解答