Volley是Google推出的一個網絡請求庫,已經被放到了Android源碼中,地址在這里,先看使用方法
RequestQueue mRequestQueue = Volley.newRequestQueue(context); JsonObjectRequest req = new JsonObjectRequest(URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { VolleyLog.v("Response:%n %s", response.toString(4)); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.e("Error: ", error.getMessage()); } }); mRequestQueue.add(req);
詳細的使用方法就不說了,網上很多,可以看下這個,這里只大概介紹一下Volley的工作方法,就從上面的例子開始。
我們接觸到的Volley的核心就兩個,從名字就可以看出其用途。
- RequestQueue
- Request
前面我們看到RequestQueue是通過Volley的方法newRequestQueue獲得的,Volley類的唯一作用就是獲取RequestQueue的實例,而我們完全可以自己new RequestQueue,不知道為什么不把這兩個類合並了。
/** * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. * * @param context A {@link Context} to use for creating the cache dir. * @param stack An {@link HttpStack} to use for the network, or null for default. * @return A started {@link RequestQueue} instance. */ 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 { // Prior to Gingerbread, HttpUrlConnection was unreliable. // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } } Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); queue.start(); return queue; } /** * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. * * @param context A {@link Context} to use for creating the cache dir. * @return A started {@link RequestQueue} instance. */ public static RequestQueue newRequestQueue(Context context) { return newRequestQueue(context, null); }
HttpStack
在newRequestQueue里出現了幾個重要的概念,首先可以看到newRequestQueue有一個重載方法,接收一個HttpStack的實例,HttpStack只有一個方法:performRequest,用來執行網絡請求並返回HttpResponse,如果不傳這個參數就根據API Level自己選擇:
- 當 API >= 9 即2.3及以后的系統使用HurlStack
- 2.3以前的系統使用HttpClientStack
從這兩個類的名字就大概知道了它們的區別了:HurlStack內部使用HttpURLConnection執行網絡請求,HttpClientStack內部使用HttpClient執行網絡請求,至於為什么么這樣,可以自備梯子看這篇文章。
Network
Network是請求網絡的接口,只有一個實現類BasicNetwork,只有一個方法performRequest,執行Request返回NetworkResponse。
Network和HttpStack接口都只有一個方法,從方法的名字就可以看出它們的區別,Network.performRequest收Request參數返回om.android.volley.NetworkResponse,HttpStack.performRequest返回org.apache.http.HttpResponse,層次更低,所以應該是Network.performRequest中調用HttpStack.performRequest執行實際的請求,並將HttpStack.performRequest返回的org.apache.http.HttpResponse封裝成com.android.volley.NetworkResponse返回。
Cache
Volley中使用Cache接口的子類DiskBasedCache做緩存,這是一個文件緩存,Cache接口有一個initialize方法用來初始化緩存,這個方法可能會執行耗時操作,需要在后台線程中執行,看DiskBasedCache可以知道,當它將緩存寫到文件時,在文件的頭部寫了一些Header信息,在initialize時就會將這些Header信息讀入內存中。
在Request類中有一個方法叫parseNetworkResponse,Request的子類會覆寫這個方法解析網絡請求的結果,在這個方法中會調用
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
返回Response<T>,並通過HttpHeaderParse.parseCacheHeaders解析Cache.Entity,即生成緩存對象,在parseaCheHeaders中會根據網絡請求結果中的Header中的Expires、Cache-Control等信息判斷是否需要緩存,如果不需要就返回null不緩存。
當對請求做了緩存后,沒網的情況下也可以得到數據。
Cache還有一個子類叫NoCache,get方法返回Null,其他方法都是空的,所以使用NoCache就表示不用緩存。
RequestQueue
public RequestQueue(Cache cache, Network network, int threadPoolSize) {
this(cache, network, threadPoolSize, new ExecutorDelivery(new Handler(Looper.getMainLooper()))); } /** * Creates the worker pool. Processing will not begin until {@link #start()} is called. * * @param cache A Cache to use for persisting responses to disk * @param network A Network interface for performing HTTP requests */ public RequestQueue(Cache cache, Network network) { this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE); } 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(); } }
RequestQueue是請求隊列,負責分發請求,取緩存或讀網絡,所以其構造函數中需要一個Cache對象和一個Network對象,還有一個ResponseDelivery對象用於派發結果。
新建RequestQueue后要調用它的start方法,在start中會新建一個CacheDispatcher和幾個NetworkDispatcher分別處理緩存與網絡請求
通過RequestQueue的add方法添加請求:
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方法有以下幾個步驟:
- 判斷當前的Request是否使用緩存,如果不使用緩存直接加入網絡請求隊列mNetworkQueue返回
- 如果使用緩存,判斷之前是否有執行相同的請求且還沒有返回結果
- 如果第2步的判斷是true,將此請求加入mWaitingRequests隊列,不再重復請求,在上一個請求返回時直接發送結果
- 如果第2步的判斷是false,將請求加入緩存隊列mCacheQueue,同時加入mWaitingRequests中用來當下個請求來時做第2步中的判斷
RequestQueue.add的任務就是這些,可以看到,它並沒有執行任何實際的請求操作,包括判斷緩存與請求網絡,直正的操作是接下來要說的兩個類執行的。
CacheDispatcher
mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
在RequestQueue.add方法中,如果使用緩存直接就將Request放入緩存隊列mCacheQueue中了,使用mCacheQueue的位置就是CacheDispatcher,CacheDispatcher的構造函數中傳入了緩存隊列mCacheQueue、網絡隊列mNetworkQueue、緩存對象mCache及結果派發器mDelivery。
CacheDispatcher繼承自Thread,當被start后就執行它的run方法,代碼不貼了,主要完成以下工作:
- 從mCacheQueue取請求Request
- 每個Request都可以從中得到CacheKey,看對應的CacheKey在緩存mCache中是否存在
- 如果緩存不存在就加到網絡隊列mNetworkQueue中繼續取下一個請求
- 如果緩存存在,判斷是否過期
- 如果過期了就加入網絡隊列mNetworkQueue中繼續取下一個請求
- 如果沒過期,看是否需要刷新
- 如果不需要刷新,直接派發結果
- 如果需要刷新,調用mDelivery.postResponse派發結果,並將Request加入網絡隊列重新請求最新數據
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. } } });
NetworkDispatcher
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery);
NetworkDispatcher的工作方法同CacheDispatcher一樣,繼承自Thread,當被start后,不停地從mNetworkQueue取請求,然后通過Network接口請求網絡。
當拿到請求結果后,如果服務器返回304(自上次請求后結果無變化)並且結果已經通過緩存派發了(即這次是讀了緩存后的Refresh),那么什么也不做,否則調用Request的parseNetworkResponse解析請求結果,如果需要進行緩存,並派發結果
ResponseDelivery
派發請求結果的接口,有一個子類ExecutorDelivery執行實際操作,構造ExecutorDelivery的對象時需要一個Handler對象,當向ExecutorDelivery請求派發結果時會向這個Handler post消息。
Request
Request表示一個請求,支持四種優先級:LOW、NORMAL、HIGH、IMMEDIATE,主要有以下幾個方法:
- getHeaders 獲取請求Http Header列表
- getBodyContentType 請求類型,如application/x-www-form-urlencoded; charset=utf-8
- getBody 將要發送的POST或PUT請求的內容
- getParams,獲取POST或PUT請求的參數,如果重寫getBody的話這個就用不到了
- parseNetworkResponse 將請求結果解析成需要的類型,將NetworkResponse解析成Response<T>,NetworkResponse中的data成員即網絡請求結果為byte[]
- deliverResponse 子類需要實現,用於將結果派發至Listener
StringRequest將結果轉換成了String並Deliver至Response.Listener
@Override protected void deliverResponse(String response) { mListener.onResponse(response); } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String parsed; try { parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); } catch (UnsupportedEncodingException e) { parsed = new String(response.data); } return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); }
JsonRequest<T>
可以在發送請求時同時發送一個JSONObject參數,覆寫了getBody
@Override public byte[] getBody() { try { return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET); } catch (UnsupportedEncodingException uee) { VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, PROTOCOL_CHARSET); return null; } }
mRequestBody是構造函數里傳進來的一個String,一般是JSONObject.toString()。
JsonObjectRequest
繼承自JSONRequest<T>,將請求結果解析成JSONObject
public JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) { super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener); } @Override protected Response<JSONObject> rkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
JsonArrayRequest
同JsonObjectRequest一樣,繼承自JSONRequest<T>,只是把結果解析成JSONArray。
ClearCacheRequest
Hack性質的請求,用於清除緩存,設置為最高優先級IMMEDIATE,執行請求時會調用Request.isCanceled判斷請求是否被取消掉了,就在這里清除了緩存
@Override public boolean isCanceled() { // This is a little bit of a hack, but hey, why not. mCache.clear(); if (mCallback != null) { Handler handler = new Handler(Looper.getMainLooper()); handler.postAtFrontOfQueue(mCallback); } return true; }
Cancel
RequestQueue同樣提供了取消請求的方法。通過它的cancelAll方法。
/** * A simple predicate or filter interface for Requests, for use by * {@link RequestQueue#cancelAll(RequestFilter)}. */ public interface RequestFilter { public boolean apply(Request<?> request); } /** * 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(); } } } } /** * 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; } }); }
通過給每個請求設置一個Tag,然后通過cancelAll(final Object tag)就可以取消對應Tag的請求,也可以直接使用RequestFilter
圖片加載
通過ImageRequest、ImageLoader和NetworkImageView等類,Volley還可用於加載圖片,通過加鎖實現了同時只解析一張圖片,同時只解析一張,而不是只加載一張,網絡請求還是跟普通的請求一樣,返回的是byte數組,解析指byte[]->Bitmap,由於請求結果是byte[],大圖應該很容易內存溢出,而且不支持本地圖片,所以不考慮使用,略過。
總結
Volley的擴展應該還是比較容易的,網絡已經有各種版本擴展了,像Cache,Request等都是提供的接口,很容易有自己的實現,比如實現GsonRequest用於使用Gson解析返回的json結果:
protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String json = new String( response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success( gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } }
Volley被設計用於小的網絡請求,所以像上傳下載大文件什么的就不適合了,雖然網上已有相應的擴展,而且原生是沒有文件上傳的。
Volley還有NetImageView,ImageLoader等和加載圖片相關的,不過我個人習慣了使用UniversalImageLoader
雖然網上都說Volley速度快,易於擴展,也給出了對比數據,但總歸是要自己手工擴展,也沒看出特別大的優勢,和Android-Async-Http相比有一點不同就是2.3后使用了官方建議的HttpUrlConnection。
還有一點最主要的應該就是Volley的緩存方法了,根據進行請求時服務器返回的緩存控制Header對請求結果進行緩存,下次請求時判斷如果沒有過期就直接使用緩存加快響應速度,如果需要會再次請求服務器進行刷新,如果服務器返回了304,表示請求的資源自上次請求緩存后還沒有改變,這種情況就直接用緩存不用再次刷新頁面,不過這要服務器支持了。
當對上次的請求進行緩存后,在下次請求時即使沒有網絡也可以請求成功,關鍵的是,緩存的處理對用戶完全是透明的,對於一些簡單的情況會省去緩存相關的一些事情