編輯:關於 Android 程式設計
學會 OkHttp3 的用法之後,自然該來看看它的源碼。網上相關文章很多,我仍希望這一系列能寫得最簡潔易懂。
發請求時我們呼叫 OkHttpClient.newCall(request) 取得 Call,再執行 execute 或 enqueue。看 newCall:
@Override
public Call newCall(Request request) {
return new RealCall(this, request);
}
實際回傳的是 RealCall。異步請求 enqueue 也是 RealCall 的方法:
void enqueue(Callback responseCallback, boolean forWebSocket) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
client.dispatcher().enqueue(new AsyncCall(responseCallback, forWebSocket));
}
最終把請求交給了 Dispatcher。
/** 最大並發請求數 */ private int maxRequests = 64; /** 每個主機最大請求數 */ private int maxRequestsPerHost = 5; /** 消費者線程池 */ private ExecutorService executorService; /** 待執行的異步請求佇列 */ private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>(); /** 執行中的異步請求佇列 */ private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>(); /** 執行中的同步請求佇列 */ private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
public Dispatcher(ExecutorService executorService) {
this.executorService = executorService;
}
public Dispatcher() { }
public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
兩個構造函式:可以自訂線程池;不設定的話,會在首次請求前自行建立。這個線程池性質接近 CachedThreadPool,適合執行大量但單次耗時短的任務。
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests
&& runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
規則很清楚:執行中的請求數少於 64 且該主機請求數少於 5,就直接丟進線程池;否則先放進 readyAsyncCalls 排隊。
傳進線程池的物件就是 AsyncCall,它是 RealCall 的內部類別:
@Override
protected void execute() {
boolean signalledCallback = false;
try {
Response response = getResponseWithInterceptorChain(forWebSocket);
if (canceled) {
signalledCallback = true;
responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
signalledCallback = true;
responseCallback.onResponse(RealCall.this, response);
}
} catch (IOException e) {
if (signalledCallback) {
// 避免重複回呼
logger.log(Level.INFO, "Callback failure for " + toLoggableString(), e);
} else {
responseCallback.onFailure(RealCall.this, e);
}
} finally {
client.dispatcher().finished(this);
}
}
注意最後一行:無論結果如何都會呼叫 finished:
synchronized void finished(AsyncCall call) {
if (!runningAsyncCalls.remove(call)) throw new AssertionError("AsyncCall wasn't running!");
promoteCalls();
}
把自己從 runningAsyncCalls 移除後,接著執行 promoteCalls:
private void promoteCalls() {
if (runningAsyncCalls.size() >= maxRequests) return;
if (readyAsyncCalls.isEmpty()) return;
for (Iterator i = readyAsyncCalls.iterator(); i.hasNext(); ) {
AsyncCall call = i.next();
if (runningCallsForHost(call) < maxRequestsPerHost) {
i.remove();
runningAsyncCalls.add(call);
executorService().execute(call);
}
if (runningAsyncCalls.size() >= maxRequests) return;
}
}
也就是從待執行佇列補位下一個請求,讓線程池隨時維持在有效工作量。回到 AsyncCall.execute,getResponseWithInterceptorChain 回傳 Response——顯然真正的網絡動作就在這裡。
private Response getResponseWithInterceptorChain(boolean forWebSocket) throws IOException {
Interceptor.Chain chain = new ApplicationInterceptorChain(0, originalRequest, forWebSocket);
return chain.proceed(originalRequest);
}
ApplicationInterceptorChain 同樣是 RealCall 的內部類別,接著執行它的 proceed:
@Override
public Response proceed(Request request) throws IOException {
// 若鏈上還有下一個攔截器,就呼叫它
if (index < client.interceptors().size()) {
Interceptor.Chain chain = new ApplicationInterceptorChain(index + 1, request, forWebSocket);
Interceptor interceptor = client.interceptors().get(index);
Response interceptedResponse = interceptor.intercept(chain);
if (interceptedResponse == null) {
throw new NullPointerException("application interceptor "
+ interceptor + " returned null");
}
return interceptedResponse;
}
// 沒有更多攔截器了,真正發 HTTP
return getResponse(request, forWebSocket);
}
每次從列表取出一個攔截器,多個攔截器時會在第 7 行阻塞,等待下一層返回。用 1 個與 2 個攔截器的情境模擬一下:

攔截器主要用來觀察、修改,甚至短路請求與回應,通常用於增刪或轉換 header。常見應用包括把域名替換為 IP、補上 host 標頭,或統一注入裝置 ID、版本號等公共參數。
回到最後一行:沒有更多攔截器時才會執行 getResponse。看看它做了什麼:
Response getResponse(Request request, boolean forWebSocket) throws IOException {
// 建立初始 HTTP 引擎。重試與重定向需要新的引擎
engine = new HttpEngine(client, request, false, false, forWebSocket,
null, null, null);
int followUpCount = 0;
while (true) {
if (canceled) {
engine.releaseStreamAllocation();
throw new IOException("Canceled");
}
boolean releaseConnection = true;
try {
engine.sendRequest();
engine.readResponse();
releaseConnection = false;
} catch (RequestException e) {
// 請求無法被解讀,放棄
throw e.getCause();
} catch (RouteException e) {
// 路由連線失敗,請求尚未送出
HttpEngine retryEngine = engine.recover(e.getLastConnectException(), null);
if (retryEngine != null) {
releaseConnection = false;
engine = retryEngine;
continue;
}
throw e.getLastConnectException();
} catch (IOException e) {
// 與伺服器溝通失敗,請求可能已送出
HttpEngine retryEngine = engine.recover(e, null);
if (retryEngine != null) {
releaseConnection = false;
engine = retryEngine;
continue;
}
throw e;
} finally {
if (releaseConnection) {
StreamAllocation streamAllocation = engine.close();
streamAllocation.release();
}
}
}
}
可見核心就是建立 HttpEngine,再呼叫 sendRequest 與 readResponse。
public void sendRequest() throws RequestException, RouteException, IOException {
if (cacheStrategy != null) return; // 已送過
if (httpStream != null) throw new IllegalStateException();
// 為請求補上標頭
Request request = networkRequest(userRequest);
// 取得 client 的 Cache,初始化時會讀取曾請求過的所有資訊
InternalCache responseCache = Internal.instance.internalCache(client);
// cacheCandidate:上次與伺服器互動所留下的 Response
Response cacheCandidate = responseCache != null ? responseCache.get(request) : null;
long now = System.currentTimeMillis();
cacheStrategy = new CacheStrategy.Factory(now, request, cacheCandidate).get();
networkRequest = cacheStrategy.networkRequest;
cacheResponse = cacheStrategy.cacheResponse;
if (responseCache != null) {
responseCache.trackResponse(cacheStrategy);
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // 不適用,關掉
}
// 不發網絡請求且無可用緩存 → 回 504
if (networkRequest == null && cacheResponse == null) {
userResponse = new Response.Builder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(EMPTY_BODY)
.build();
return;
}
// 不發網絡請求但緩存可用 → 直接回緩存
if (networkRequest == null) {
userResponse = cacheResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.cacheResponse(stripBody(cacheResponse))
.build();
userResponse = unzip(userResponse);
return;
}
// 其餘情況才真的送請求
boolean success = false;
try {
httpStream = connect();
httpStream.setHttpEngine(this);
// ... 依 contentLength 決定是否緩衝請求體
success = true;
} finally {
if (!success && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
}
緩存的實作基於 Map:key 是請求 URL 的 md5,value 是檔案中查到的緩存,頁面置換採 LRU 演算法。這裡只需知道 cacheCandidate 是一個能讀取過往 header 的 Response。
依 cacheStrategy 的運算結果得到 networkRequest 與 cacheResponse,再依兩者是否為 null 分三種處理:兩者皆 null(不發請求且無有效緩存)回 504;networkRequest 為 null(不發請求且緩存可用)直接回緩存;其餘則發請求。
接著看 readResponse:
public void readResponse() throws IOException {
// ... 讀取網絡回應
networkResponse = readNetworkResponse();
// 把回應標頭寫入 Cookie
receiveHeaders(networkResponse.headers());
// 若同時有緩存,則進行條件式 GET
if (cacheResponse != null) {
if (validate(cacheResponse, networkResponse)) {
userResponse = cacheResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.headers(combine(cacheResponse.headers(), networkResponse.headers()))
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
releaseStreamAllocation();
InternalCache responseCache = Internal.instance.internalCache(client);
responseCache.trackConditionalCacheHit();
responseCache.update(cacheResponse, stripBody(userResponse));
userResponse = unzip(userResponse);
return;
} else {
closeQuietly(cacheResponse.body());
}
}
userResponse = networkResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
if (hasBody(userResponse)) {
maybeCache();
userResponse = unzip(cacheWritingResponse(storeRequest, userResponse));
}
}
流程是:解析 HTTP 標頭 → 若有緩存且驗證通過則用緩存並更新它 → 否則採用網絡結果。
validate 怎麼判斷緩存是否可用?
private static boolean validate(Response cached, Response network) {
// 伺服器回 304 表示緩存有效
if (network.code() == HTTP_NOT_MODIFIED) {
return true;
}
// 用 Last-Modified 比較新舊
Date lastModified = cached.headers().getDate("Last-Modified");
if (lastModified != null) {
Date networkLastModified = network.headers().getDate("Last-Modified");
if (networkLastModified != null
&& networkLastModified.getTime() < lastModified.getTime()) {
return true;
}
}
return false;
}
若緩存過期或強制放棄緩存,判斷權就完全交給伺服器:客戶端只發條件式 GET,有效則回 304 Not Modified,否則回傳 body。條件式 GET 有 Last-Modified-Date 與 ETag 兩種,這裡採用前者。
回到 getResponse 的 catch 區塊,當發生 IOException 或 RouteException 時會呼叫 recover:
public HttpEngine recover(IOException e, Sink requestBodyOut) {
if (!streamAllocation.recover(e, requestBodyOut)) {
return null;
}
if (!client.retryOnConnectionFailure()) {
return null;
}
StreamAllocation streamAllocation = close();
// 失敗恢復時沿用同一組路由選擇器,但建立新連線
return new HttpEngine(client, userRequest, bufferRequestBody,
callerWritesRequestBody, forWebSocket,
streamAllocation, (RetryableSink) requestBodyOut, priorResponse);
}
最後一行重新建立了 HttpEngine 並回傳,外層 while 迴圈 continue 就完成了重連。要注意的是 recover 回傳 null 代表無法恢復,此時才會把例外往外拋。
到這裡 OkHttp 發請求的流程大致講完了,整體調用鏈整理如下:

一句話總結:newCall 產生 RealCall,enqueue 交給 Dispatcher 做並發與主機限流,AsyncCall 在線程池中透過攔截器鏈往下走,最後由 HttpEngine 負責緩存策略、實際收发與失敗重連。
Material Design 風格控件全攻略:CoordinatorLayout、Toolbar 與 NavigationView
想使用 Material Design(MD)風格控件,第一步得先在 Gradle 中引入 Support Design Library,例如: compile com.
Android 監聽 Home 鍵的兩種做法
以下兩種方式都能勝任返回鍵、Home 鍵與多任務鍵的監聽,但能力範圍不同,依需求挑一種即可。 做法一:註冊廣播監聽 Home 鍵與多任務鍵 效果示意: 建立一個廣播接收
Android 開發:Retrofit 搭配 Gson 解析 JSON 實作(Android Studio 篇)
本文說明主要都放在程式碼與截圖上,直接照著做即可。 唯一要留意的是:JSON 相關的函式庫或圖片載入套件,需要自行到官網下載。另外這裡還會用到一個 Google 提供的註
設計模式筆記(6):適配器模式,Android UI 架構的靈魂
適配器模式(Adapter Pattern)是開發中出現頻率最高的模式之一——ListView 和 RecyclerView 的 Adapter 就是最直觀的例子。 生活