源碼下載地址:https://github.com/code-study/android-volley-analysis
一尸变、原理
Volley有兩個(gè)調(diào)度器绪氛,緩存請(qǐng)求調(diào)度器和網(wǎng)絡(luò)請(qǐng)求調(diào)度器,兩個(gè)調(diào)度器均是Thread的子類驯耻,且擁有各自的隊(duì)列;初始化Volley時(shí)啟動(dòng)兩個(gè)線程,在子線程中while(ture)循環(huán)煮甥,將請(qǐng)求加入隊(duì)列,通過隊(duì)列阻塞的方式藕赞,控制請(qǐng)求流程成肘。
二、源碼分析
1斧蜕、使用方式
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
2双霍、流程分析
(1)Volley.java
首先創(chuàng)建RequestQueue的實(shí)例;創(chuàng)建網(wǎng)絡(luò)請(qǐng)求,再將其封裝洒闸;創(chuàng)建緩存機(jī)制并設(shè)置緩存目錄染坯;
public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) { // context.getCacheDir() : /data/data/com.android.volley.test/cache 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 : com.android.volley.test/1
userAgent = packageName + "/" + info.versionCode;
} catch (NameNotFoundException e) {
}
//創(chuàng)建網(wǎng)絡(luò)請(qǐng)求
if (stack == null) {
//在 Froyo(2.2) 之前,HttpURLConnection 有個(gè)重大 Bug丘逸,調(diào)用 close() 函數(shù)會(huì)影響連接池单鹿,導(dǎo)致連接復(fù)用失效,所以在2.2之前使用 HttpURLConnection 需要關(guān)閉 keepAlive深纲。
// Gingerbread(2.3) HttpURLConnection 默認(rèn)開啟了 gzip 壓縮仲锄,提高了 HTTPS 的性能,Ice Cream Sandwich(4.0) HttpURLConnection 支持了請(qǐng)求結(jié)果緩存
if (Build.VERSION.SDK_INT >= 9) {
//HttpURLConnection
stack = new HurlStack();
} else {
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
//HttpClient
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
// 封裝請(qǐng)求
Network network = new BasicNetwork(stack);
//創(chuàng)建請(qǐng)求隊(duì)列
RequestQueue queue;
if (maxDiskCacheBytes <= -1) {
// No maximum size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
} else {
// Disk cache size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
}
queue.start();
return queue;
}
****詳細(xì)分析:** 首先設(shè)置緩存文件地址湃鹊,用于緩存請(qǐng)求回來的結(jié)果儒喊。 創(chuàng)建網(wǎng)絡(luò)請(qǐng)求,若android版本大于等于9的話币呵,則使用HurlStack(實(shí)際是HttpURLConnection)怀愧,否則使用HttpClientStack(實(shí)際是HttpClient),原因是在 Froyo(2.2) 之前富雅,HttpURLConnection 有個(gè)重大 Bug掸驱,調(diào)用 close() 函數(shù)會(huì)影響連接池,導(dǎo)致連接復(fù)用失效没佑,所以在2.2之前使用 HttpURLConnection 需要關(guān)閉 keepAlive毕贼。Gingerbread(2.3) HttpURLConnection 默認(rèn)開啟了 gzip 壓縮,提高了 HTTPS 的性能蛤奢,Ice Cream Sandwich(4.0) HttpURLConnection 支持了請(qǐng)求結(jié)果緩存鬼癣。 將網(wǎng)絡(luò)請(qǐng)求封裝到BasicNetWork,用于真正執(zhí)行請(qǐng)求啤贩,后面將會(huì)詳細(xì)說明待秃。 創(chuàng)建RequestQueue并start,可以設(shè)置最大緩存bytes(maxDiskCacheBytes)痹屹,默認(rèn)是5M章郁。
(2)RequestQueue.java
Volley的核心是調(diào)度線程,首先終止所有的調(diào)度線程志衍,即調(diào)用所有調(diào)度器的interrupt(調(diào)度器均為Thread)暖庄; 啟用一個(gè)緩存線程,和四個(gè)網(wǎng)絡(luò)線程楼肪;兩種調(diào)度線程run方法均開啟while(true)循環(huán)培廓,通過隊(duì)列阻塞方式控制請(qǐng)求流程,下面會(huì)詳情說明春叫。
public void start() {
//終止所有調(diào)度器線程
stop(); // Make sure any currently running dispatchers are stopped.
// Create the cache dispatcher and start it.
// 緩存調(diào)度器
mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
mCacheDispatcher.start();
// Create network dispatchers (and corresponding threads) up to the pool size.
// 網(wǎng)絡(luò)請(qǐng)求調(diào)度器,默認(rèn)開啟DEFAULT_NETWORK_THREAD_POOL_SIZE(4)個(gè)線程肩钠,相當(dāng)于線程池
for (int i = 0; i < mDispatchers.length; i++) {
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery);
mDispatchers[i] = networkDispatcher;
networkDispatcher.start();
}
}
接下來調(diào)用RequestQueue的add方法泣港,將請(qǐng)求加入隊(duì)列;如果不需要緩存則加入網(wǎng)絡(luò)隊(duì)列价匠,否則加入緩存隊(duì)列当纱,相應(yīng)的調(diào)度線程獲取隊(duì)列元素解除阻塞,會(huì)往下執(zhí)行相應(yīng)的邏輯霞怀。加入緩存隊(duì)列之前需要先判斷是否有相同的請(qǐng)求在執(zhí)行中惫东,若有則加入等待隊(duì)列,待前一次請(qǐng)求執(zhí)行完之后毙石,再執(zhí)行廉沮。
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); //為Request設(shè)置請(qǐng)求隊(duì)列
//將請(qǐng)求add到當(dāng)前請(qǐng)求隊(duì)列中
synchronized (mCurrentRequests) {
mCurrentRequests.add(request);
}
// Process requests in the order they are added.
//設(shè)置唯一的序列號(hào)
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()) {
//不緩存帚呼,跳過緩存隊(duì)列直接請(qǐng)求數(shù)據(jù)
mNetworkQueue.add(request);
return request;
}
// Insert request into stage if there's already a request with the same cache key in flight.
//緩存,首先判斷是否有相同請(qǐng)求正在處理
synchronized (mWaitingRequests) {
String cacheKey = request.getCacheKey();
//有相同請(qǐng)求正在處理
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);
//處理等待隊(duì)列空數(shù)據(jù),加入到等待隊(duì)列
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.
// 創(chuàng)建新的等待當(dāng)前請(qǐng)求的空隊(duì)列添加到當(dāng)前請(qǐng)求緩存隊(duì)列中
mWaitingRequests.put(cacheKey, null);
mCacheQueue.add(request);
}
return request;
}
}
****詳細(xì)分析:** 有兩個(gè)隊(duì)列需要說明一下奶陈,mCurrentRequests正在被請(qǐng)求的隊(duì)列,在調(diào)用上述add的時(shí)候卖宠,需將當(dāng)前請(qǐng)求加入到此隊(duì)列滤灯,主要作用是取消請(qǐng)求坪稽;另一個(gè)是mWaitingRequests,作用是避免多次發(fā)送相同請(qǐng)求鳞骤,若當(dāng)前沒有相同請(qǐng)求正在處理窒百,則將當(dāng)前請(qǐng)求key中加入空隊(duì)列;當(dāng)請(qǐng)求結(jié)束時(shí)豫尽,移除mWaitingRequests中的當(dāng)前請(qǐng)求key中的等待請(qǐng)求篙梢,并將當(dāng)前key中的所有等待請(qǐng)求加入到緩存隊(duì)列(可見RequestQueue中的finish)。
(3)NetworkDispatcher和CacheDispatcher
上面說到請(qǐng)求加入隊(duì)列后會(huì)有相應(yīng)的調(diào)度線程來處理美旧,這也是Volley中最重要的部分
NetworkDispatcher.java 先看一下網(wǎng)絡(luò)調(diào)度線程渤滞;在run中執(zhí)行while(true),若網(wǎng)絡(luò)隊(duì)列中沒有元素則阻塞隊(duì)列榴嗅,直到隊(duì)列有元素加入妄呕,取出元素request,通過網(wǎng)絡(luò)請(qǐng)求嗽测,將返回的response加入緩存(若需緩存)且將結(jié)果分發(fā)給上層回調(diào)绪励。
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Request<?> request;
while (true) {
long startTimeMs = SystemClock.elapsedRealtime();
// release previous request object to avoid leaking request object when mQueue is drained.
request = null;
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.
// 如果請(qǐng)求被中途取消
if (request.isCanceled()) {
request.finish("network-discard-cancelled");
continue;
}
// 流量統(tǒng)計(jì)用的
addTrafficStatsTag(request);
// Perform the network request.
// 請(qǐng)求數(shù)據(jù)
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()) {
//如果是相同的請(qǐng)求,那么服務(wù)器就返回一次響應(yīng)
request.finish("not-modified");
continue;
}
// Parse the response here on the worker thread.
// 解析響應(yīng)數(shù)據(jù)
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) {
// 緩存數(shù)據(jù)
mCache.put(request.getCacheKey(), response.cacheEntry);
request.addMarker("network-cache-written");
}
// Post the response back.
//確認(rèn)請(qǐng)求要被分發(fā)
request.markDelivered();
//發(fā)送請(qǐng)求
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);
}
}
}
CacheDispatcher.java 接下來看一下緩存調(diào)度線程唠粥;在run中執(zhí)行while(true)优炬,若緩存隊(duì)列中沒有元素則阻塞隊(duì)列,直到隊(duì)列有元素加入厅贪,取出元素request,通過key取出緩存雅宾,若緩存無數(shù)據(jù)或者已過期則加入網(wǎng)絡(luò)隊(duì)列進(jìn)行網(wǎng)絡(luò)請(qǐng)求养涮,否則取出緩存封裝成response葵硕;若緩存不需要更新則直接分發(fā)給上層回調(diào),否則再次提交網(wǎng)絡(luò)請(qǐng)求贯吓。
@Override
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();
Request<?> request;
while (true) {
// release previous request object to avoid leaking request object when mQueue is drained.
request = null;
try {
// Take a request from the queue.
// 從緩存隊(duì)列中取出請(qǐng)求
request = mCacheQueue.take();
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
return;
}
continue;
}
try {
request.addMarker("cache-queue-take");
// If the request has been canceled, don't bother dispatching it.
// 取消請(qǐng)求
if (request.isCanceled()) {
request.finish("cache-discard-canceled");
continue;
}
// Attempt to retrieve this item from cache.
Cache.Entry entry = mCache.get(request.getCacheKey());
//緩存已過期(包括expired與Soft-expired)
// 無緩存數(shù)據(jù)懈凹,則加入網(wǎng)絡(luò)請(qǐng)求
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.
// 判斷緩存的新鮮度,過期了,加入網(wǎng)絡(luò)請(qǐng)求
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");
//從緩存中取出請(qǐng)求響應(yīng)并進(jìn)行解析
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.
// 緩存沒有Soft-expired悄谐,則直接通過mDelivery將解析好的結(jié)果交付給請(qǐng)求發(fā)起者
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.
final Request<?> finalRequest = request;
//需要刷新,那么就再次提交網(wǎng)絡(luò)請(qǐng)求...獲取服務(wù)器的響應(yīng)...
mDelivery.postResponse(request, response, new Runnable() {
@Override
public void run() {
try {
// 網(wǎng)絡(luò)來更新請(qǐng)求響應(yīng)
mNetworkQueue.put(finalRequest);
} catch (InterruptedException e) {
// Not much we can do about this.
}
}
});
}
} catch (Exception e) {
VolleyLog.e(e, "Unhandled exception %s", e.toString());
}
}
}
****詳細(xì)分析:** 有兩個(gè)隊(duì)列需要說明一下介评,mCurrentRequests正在被請(qǐng)求的隊(duì)列,在調(diào)用上述add的時(shí)候爬舰,需將當(dāng)前請(qǐng)求加入到此隊(duì)列们陆,主要作用是取消請(qǐng)求;另一個(gè)是mWaitingRequests情屹,作用是避免多次發(fā)送相同請(qǐng)求坪仇,若當(dāng)前沒有相同請(qǐng)求正在處理,則將當(dāng)前請(qǐng)求key中加入空隊(duì)列垃你;當(dāng)請(qǐng)求結(jié)束時(shí)椅文,移除mWaitingRequests中的當(dāng)前請(qǐng)求key中的等待請(qǐng)求,并將當(dāng)前key中的所有等待請(qǐng)求加入到緩存隊(duì)列(可見RequestQueue中的finish)惜颇。
(4)BasicNetwork.java
封裝HttpStack網(wǎng)絡(luò)請(qǐng)求皆刺,實(shí)際由HttpStack實(shí)現(xiàn)。
@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
//獲取請(qǐng)求開始的時(shí)間 debug用的
long requestStart = SystemClock.elapsedRealtime();
//如果發(fā)生超時(shí)凌摄,認(rèn)證失敗等錯(cuò)誤羡蛾,進(jìn)行重試操作,直到成功望伦、拋出異常(不滿足重試策略等)結(jié)束
while (true) {
HttpResponse httpResponse = null;
//請(qǐng)求內(nèi)容對(duì)象
byte[] responseContents = null;
//用于保存響應(yīng)數(shù)據(jù)報(bào)的Header中的數(shù)據(jù)
Map<String, String> responseHeaders = Collections.emptyMap();
try {
// Gather headers. 保存緩存下來的Header
Map<String, String> headers = new HashMap<String, String>();
// 添加請(qǐng)求頭部的過程
addCacheHeaders(headers, request.getCacheEntry());
// 執(zhí)行請(qǐng)求
httpResponse = mHttpStack.performRequest(request, headers);
//獲取響應(yīng)狀態(tài)
StatusLine statusLine = httpResponse.getStatusLine();
//響應(yīng)狀態(tài)碼
int statusCode = statusLine.getStatusCode();
//獲取響應(yīng)后的Header中的所有數(shù)據(jù)
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
// 304:表示從上次訪問后林说,服務(wù)器數(shù)據(jù)沒有改變,則從Cache中拿數(shù)據(jù)
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);
}
// Handle moved resources
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
String newUrl = responseHeaders.get("Location");
request.setRedirectUrl(newUrl);
}
// 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.
//由于204響應(yīng)時(shí)不返回?cái)?shù)據(jù)信息的,返回空數(shù)據(jù)
responseContents = new byte[0];
}
// if the request is slow, log it.
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
//如果一個(gè)請(qǐng)求的時(shí)間超過了指定的緩慢請(qǐng)求時(shí)間屯伞,那么需要顯示這個(gè)時(shí)間,debug
logSlowRequests(requestLifetime, request, responseContents, statusLine);
//如果請(qǐng)求狀態(tài)出現(xiàn)錯(cuò)誤,bug
//if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
if (statusCode < 200 || statusCode > 299) {
throw new IOException();
}
// 返回header+body數(shù)據(jù)
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);
}
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(), request.getUrl());
} else {
VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
}
if (responseContents != null) {
networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
//請(qǐng)求需要進(jìn)行驗(yàn)證腿箩,或者是需要授權(quán)異常處理
if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
//嘗試重試策略方法
attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
} else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
} else {
// TODO: Only throw ServerError for 5xx status codes.
throw new ServerError(networkResponse);
}
} else {
throw new NetworkError(e);
}
}
}
}
****詳細(xì)分析:** 在網(wǎng)絡(luò)分發(fā)器中用到了這里,主要通過這個(gè)方法來獲取請(qǐng)求結(jié)果劣摇。此方法中也有個(gè)while(true)循環(huán)珠移,如果發(fā)生超時(shí),認(rèn)證失敗等錯(cuò)誤末融,進(jìn)行重試操作钧惧,直到成功、拋出異常(不滿足重試策略等)結(jié)束勾习;實(shí)際由HttpStack執(zhí)行請(qǐng)求浓瞪,將請(qǐng)求結(jié)果封裝到NetworkResponse中(之后通過Request子類將其轉(zhuǎn)成需要的類型分發(fā)給上層回調(diào))。
(5)HttpClientStack和HurlStack
在上述調(diào)度線程中巧婶,實(shí)際處理請(qǐng)求獲取到請(qǐng)求的結(jié)果的類就是這兩個(gè)乾颁,這兩個(gè)類同implements了HttpStack接口涂乌,這個(gè)接口只有一個(gè)方法需要實(shí)現(xiàn),performRequest處理請(qǐng)求英岭。
HurlStack.java performRequest內(nèi)由HttpURLConnection處理網(wǎng)絡(luò)請(qǐng)求湾盒,返回response
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError { String url = request.getUrl();
//添加head:請(qǐng)求head+額外的head
HashMap<String, String> map = new HashMap<String, String>();
map.putAll(request.getHeaders());
map.putAll(additionalHeaders);
//目前沒有使用到,對(duì)url進(jìn)行重寫,重寫的好處使url更加的保密诅妹,安全
if (mUrlRewriter != null) {
String rewritten = mUrlRewriter.rewriteUrl(url);
if (rewritten == null) {
throw new IOException("URL blocked by rewriter: " + url);
}
url = rewritten;
}
URL parsedUrl = new URL(url);
// 建立連接
HttpURLConnection connection = openConnection(parsedUrl, request);
// 設(shè)置請(qǐng)求的相關(guān)屬性
for (String headerName : map.keySet()) {
connection.addRequestProperty(headerName, map.get(headerName));
}
//請(qǐng)求的方式去執(zhí)行相關(guān)的方法
setConnectionParametersForRequest(connection, request);
// Initialize HttpResponse with data from the HttpURLConnection.
//獲取協(xié)議版本
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
//響應(yīng)碼
int responseCode = connection.getResponseCode();
// 有的接口返回401罚勾,connection.getResponseCode(responseCode=401)就會(huì)拋出IOException
// 解決方案 : http://blog.csdn.net/kufeiyun/article/details/44646145
// http://stackoverflow.com/questions/30476584/android-volley-strange-error-with-http-code-401-java-io- ioexception-no-authe
if (responseCode == -1) {
// -1 is returned by getResponseCode() if the response code could not be retrieved.
// Signal to the caller that something was wrong with the connection.
throw new IOException("Could not retrieve response code from HttpUrlConnection.");
}
//響應(yīng)信息
StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage());
//響應(yīng)狀態(tài)
BasicHttpResponse response = new BasicHttpResponse(responseStatus);
//獲取響應(yīng)中的實(shí)體
if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
response.setEntity(entityFromConnection(connection));
}
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
if (header.getKey() != null) {
Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
response.addHeader(h);
}
}
return response;
}
HttpClientStack performRequest內(nèi)由HttpClient處理網(wǎng)絡(luò)請(qǐng)求,返回response
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
//創(chuàng)建請(qǐng)求
HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
//添加head
addHeaders(httpRequest, additionalHeaders);
addHeaders(httpRequest, request.getHeaders());
//準(zhǔn)備請(qǐng)求回調(diào)
onPrepareRequest(httpRequest);
HttpParams httpParams = httpRequest.getParams();
int timeoutMs = request.getTimeoutMs();
// TODO: Reevaluate this connection timeout based on more wide-scale
// data collection and possibly different for wifi vs. 3G.
// 設(shè)置連接超時(shí)時(shí)間5S
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
// 設(shè)置請(qǐng)求超時(shí),默認(rèn)設(shè)置2.5s
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
// 執(zhí)行
return mClient.execute(httpRequest);
}
(6)ResponseDelivery和ExecutorDelivery
在調(diào)度線程中獲取到結(jié)果后吭狡,當(dāng)然就需要分發(fā)結(jié)果返回給上層回調(diào)處理尖殃,分發(fā)器就是ExecutorDelivery,其中ResponseDelivery是ExecutorDelivery需要實(shí)現(xiàn)的接口赵刑,此接口中只包含請(qǐng)求成功和失敗的處理方法分衫。在ExecutorDelivery中使用了線程池的管理,不用每次創(chuàng)建新的線 程般此,重復(fù)使用已有線程即可蚪战,節(jié)省內(nèi)存。
public ExecutorDelivery(final Handler handler) {
// Make an Executor that just wraps the handler.
mResponsePoster = new Executor() {
@Override
public void execute(Runnable command) {
//傳入的Handler與主線程綁定了铐懊,所以分發(fā)消息是在主線程中
handler.post(command);
}
};
}
在主線程的runnable中分發(fā)網(wǎng)絡(luò)請(qǐng)求結(jié)果給listener 將網(wǎng)絡(luò)請(qǐng)求的結(jié)果返回給上層回調(diào)邀桑;若有附加線程則啟動(dòng),主要在緩存調(diào)度器中使用科乎,若需要刷新請(qǐng)求則在附件線程中重新執(zhí)行網(wǎng)絡(luò)請(qǐng)求壁畸。
private class ResponseDeliveryRunnable implements Runnable {
/**
* 請(qǐng)求
*/
private final Request mRequest;
/**
* 響應(yīng)
*/
private final Response mResponse;
/**
* 其他線程
*/
private final Runnable mRunnable;
public ResponseDeliveryRunnable(Request request, Response response, Runnable runnable) {
mRequest = request;
mResponse = response;
mRunnable = runnable;
}
@SuppressWarnings("unchecked")
@Override
public void run() {
// If this request has canceled, finish it and don't deliver.
// 如果請(qǐng)求被中斷,那么就不需要發(fā)送響應(yīng)了
if (mRequest.isCanceled()) {
mRequest.finish("canceled-at-delivery");
return;
}
// Deliver a normal response or error, depending.
// 如果服務(wù)器響應(yīng)成功茅茂,中途沒有錯(cuò)誤的發(fā)生
if (mResponse.isSuccess()) {
// 將服務(wù)器返回的結(jié)果發(fā)送給客戶端
mRequest.deliverResponse(mResponse.result);
} else {
// 把錯(cuò)誤發(fā)送給客戶端
mRequest.deliverError(mResponse.error);
}
// If this is an intermediate response, add a marker, otherwise we're done
// and the request can be finished.
// 中間響應(yīng)
if (mResponse.intermediate) {
mRequest.addMarker("intermediate-response");
} else {
//請(qǐng)求結(jié)束
mRequest.finish("done");
}
// If we have been provided a post-delivery runnable, run it.
// 啟動(dòng)附加線程
if (mRunnable != null) {
mRunnable.run();
}
}
}
(7)Request
接下來看一下我們一直提到的Request捏萍,Volley中Request的子類:ClearCacheRequest、JsonRequest空闲、JsonArrayRequest令杈、JsonObjectRequest、ImageRequest碴倾、StringRequest 由于調(diào)度隊(duì)列中的請(qǐng)求隊(duì)列和網(wǎng)絡(luò)隊(duì)列都是優(yōu)先級(jí)隊(duì)列逗噩,其中的元素就是Request,故Request實(shí)現(xiàn)了Comparable接口跌榔,即需要實(shí)現(xiàn)compareTo异雁,此方法主要作用是排列請(qǐng)求的優(yōu)先級(jí):優(yōu)先級(jí)越高越前、優(yōu)先級(jí)相同則根據(jù)序號(hào)來排僧须、序號(hào)越低越前纲刀。 Request中有兩個(gè)方法需要子類實(shí)現(xiàn)。parseNetworkResponse(NetworkResponse response):將原始的請(qǐng)求結(jié)果封裝成所需要的數(shù)據(jù)類型担平;deliverResponse:將請(qǐng)求結(jié)果分發(fā)給上層回調(diào)處理示绊。 各子類的實(shí)現(xiàn)較為簡單芥挣,就不做詳細(xì)說明了。
@Override
public int compareTo(Request<T> other) {
Priority left = this.getPriority();
Priority right = other.getPriority();
//優(yōu)先級(jí)越高耻台,在請(qǐng)求隊(duì)列中排得越前,相同優(yōu)先級(jí)的序號(hào)越低空另,排得越前盆耽。
// High-priority requests are "lesser" so they are sorted to the front.
// Equal priorities are sorted by sequence number to provide FIFO ordering.
return left == right ?
this.mSequence - other.mSequence :
right.ordinal() - left.ordinal();
//ordinal():回此枚舉常量的序數(shù),從0開始,下標(biāo)
}