Okhttp3 儼然已成爲Android的主流網絡請求開源框架,它的設計很是巧妙,並且很是靈活,功能強大.它有以下默認特性:java
如今的Android項目基本上都是以OkHttp來進行高效的網絡請求.固然,在使用的同時咱們須要去研究它的底層實現,從而讓咱們寫出更好的代碼.git
這裏簡單介紹2種,GET和POST.推薦讓 OkHttpClient 保持單例,用同一個 OkHttpClient 實例來執行你的全部請求,由於每個 OkHttpClient 實例都擁有本身的鏈接池和線程池,重用這些資源能夠減小延時和節省資源,若是爲每一個請求建立一個 OkHttpClient實例,顯然就是一種資源的浪費。github
public static final String URL = "http://www.baidu.com";
private OkHttpClient mOkHttpClient = new OkHttpClient();
private final Request mRequest = new Request.Builder().url(URL).build();
@Override
public void request() {
mOkHttpClient.newCall(mRequest)
//異步請求
.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.w(TAG, "onResponse: " + response.body().string());
}
});
}
複製代碼
public static final String URL = "https://api.github.com/markdown/raw";
private OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
.build();
MediaType mMediaType = MediaType.parse("text/x-markdown; charset=utf-8");
String requestBody = "I am xfhy.";
private final Request mRequest = new Request.Builder()
.url(URL)
.post(RequestBody.create(mMediaType, requestBody))
.build();
@Override
public void request() {
//每個Call(其實現是RealCall)只能執行一次,不然會報異常
mOkHttpClient.newCall(mRequest).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.w(TAG, "onResponse: " + response.body().string());
}
});
}
複製代碼
使用OkHttp3請求網絡仍是比較簡單,並且異步請求也比較輕鬆.web
正如名字所描述的,OkHttpClient像是一個請求網絡的客戶端.它內部有不少不少的配置信息(支持協議、任務調度器、鏈接池、超時時間等),經過構造器模式初始化的這些配置信息.(這裏穿插一下,正如你所看到的這種一個類裏面不少不少屬性須要初始化的,通常就用構造器模式)api
public OkHttpClient() {
this(new Builder());
}
public Builder() {
//任務調度器
dispatcher = new Dispatcher();
//支持的協議
protocols = DEFAULT_PROTOCOLS;
connectionSpecs = DEFAULT_CONNECTION_SPECS;
eventListenerFactory = EventListener.factory(EventListener.NONE);
proxySelector = ProxySelector.getDefault();
if (proxySelector == null) {
proxySelector = new NullProxySelector();
}
cookieJar = CookieJar.NO_COOKIES;
socketFactory = SocketFactory.getDefault();
hostnameVerifier = OkHostnameVerifier.INSTANCE;
certificatePinner = CertificatePinner.DEFAULT;
proxyAuthenticator = Authenticator.NONE;
authenticator = Authenticator.NONE;
//鏈接池
connectionPool = new ConnectionPool();
dns = Dns.SYSTEM;
followSslRedirects = true;
followRedirects = true;
retryOnConnectionFailure = true;
callTimeout = 0;
//超時時間
connectTimeout = 10_000;
readTimeout = 10_000;
writeTimeout = 10_000;
pingInterval = 0;
}
複製代碼
其中Dispatcher有一個線程池,用於執行異步的請求.而且內部還維護了3個雙向任務隊列,分別是:準備異步執行的任務隊列、正在異步執行的任務隊列、正在同步執行的任務隊列.緩存
/** Executes calls. Created lazily. */
//這個線程池是須要的時候纔會被初始化
private @Nullable ExecutorService executorService;
/** Ready async calls in the order they'll be run. */ private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>(); /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
/** Running synchronous calls. Includes canceled calls that haven't finished yet. */ private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>(); public synchronized ExecutorService executorService() { if (executorService == null) { //注意,該線程池沒有核心線程,線程數量能夠是Integer.MAX_VALUE個(至關於沒有限制),超過60秒沒幹事就要被回收 executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false)); } return executorService; } 複製代碼
Request感受就是一個請求的封裝.它裏面封裝了url、method、header、body,該有的都有了.並且它也是用構造器模式來構建的,它默認的請求方式是GETbash
public final class Request {
final HttpUrl url;
final String method;
final Headers headers;
final @Nullable RequestBody body;
final Map<Class<?>, Object> tags;
public Builder() {
this.method = "GET";
this.headers = new Headers.Builder();
}
public static class Builder {
@Nullable HttpUrl url;
String method;
Headers.Builder headers;
@Nullable RequestBody body;
/** A mutable map of tags, or an immutable empty map if we don't have any. */
Map<Class<?>, Object> tags = Collections.emptyMap();
public Builder() {
this.method = "GET";
this.headers = new Headers.Builder();
}
}
複製代碼
咱們進入mOkHttpClient的newCall方法,它構造的是一個Call對象,其實是一個RealCall服務器
/** * Prepares the {@code request} to be executed at some point in the future. */
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
複製代碼
RealCall#enqueue(Callback)markdown
因此示例中的enqueue其實是RealCall中的方法cookie
@Override public void enqueue(Callback responseCallback) {
......
//將AsyncCall傳入任務調度器,
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
複製代碼
將AsyncCall(這個咱們稍後再說)傳入任務調度器,任務任務調度器會將其存入待執行的請求隊列(上面提到的readyAsyncCalls)中,而後條件容許的話再加入到運行中的請求隊列(runningAsyncCalls)中,而後將這個請求放到任務調度器中的線程池中進行消費.下面是詳細代碼
----Dispatcher#enqueue(AsyncCall)
void enqueue(AsyncCall call) {
synchronized (this) {
readyAsyncCalls.add(call);
// Mutate the AsyncCall so that it shares the AtomicInteger of an existing running call to
// the same host.
if (!call.get().forWebSocket) {
AsyncCall existingCall = findExistingCallWithHost(call.host());
if (existingCall != null) call.reuseCallsPerHostFrom(existingCall);
}
}
promoteAndExecute();
}
private boolean promoteAndExecute() {
List<AsyncCall> executableCalls = new ArrayList<>();
boolean isRunning;
synchronized (this) {
//從待執行隊列中取出來
for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
AsyncCall asyncCall = i.next();
//若是正在執行的任務>=64 那麼就算了,先緩一緩
if (runningAsyncCalls.size() >= maxRequests) break; // Max capacity.
if (asyncCall.callsPerHost().get() >= maxRequestsPerHost) continue; // Host max capacity.
i.remove();
asyncCall.callsPerHost().incrementAndGet();
executableCalls.add(asyncCall);
//加入到運行隊列中
runningAsyncCalls.add(asyncCall);
}
isRunning = runningCallsCount() > 0;
}
for (int i = 0, size = executableCalls.size(); i < size; i++) {
AsyncCall asyncCall = executableCalls.get(i);
//一個個地開始執行 executorService方法是獲取線程池
asyncCall.executeOn(executorService());
}
return isRunning;
}
//獲取線程池代碼
public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
複製代碼
上面咱們提到了不少次AsyncCall,它實際上是一個RealCall的非靜態內部類,因此能直接訪問到RealCall的屬性啥的,方便.同時,AsyncCall繼承自NamedRunnable,NamedRunnable實現了NamedRunnable.
public abstract class NamedRunnable implements Runnable {
protected final String name;
public NamedRunnable(String format, Object... args) {
this.name = Util.format(format, args);
}
@Override public final void run() {
String oldName = Thread.currentThread().getName();
Thread.currentThread().setName(name);
try {
execute();
} finally {
Thread.currentThread().setName(oldName);
}
}
protected abstract void execute();
}
複製代碼
NamedRunnable中使用了模板方法模式,子類必須實現execute方法,而且將邏輯放在execute中.而且NamedRunnable中還設置了本身線程的名字,實屬方便管理.
上面的任務調度器中執行的AsyncCall,至關於就是執行的AsyncCall的execute的邏輯
@Override protected void execute() {
boolean signalledCallback = false;
transmitter.timeoutEnter();
try {
//-----------------------重點代碼 華麗的分割線圍起來---------------------------------
//1. 經過攔截器鏈條,獲取最終的網絡請求結果
Response response = getResponseWithInterceptorChain();
//2. 標記已執行 不能再執行第二次了
signalledCallback = true;
//3. 將結果回調給調用處
responseCallback.onResponse(RealCall.this, response);
//--------------------------------------------------------
} catch (IOException e) {
if (signalledCallback) {
// Do not signal the callback twice!
Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
} else {
responseCallback.onFailure(RealCall.this, e);
}
} finally {
client.dispatcher().finished(this);
}
}
複製代碼
開始了,開始了,重點來了,經過getResponseWithInterceptorChain方法這條攔截器鏈路能夠獲取到網絡請求的結果.而後咱們經過CallBack接口回調回調用處.
在開始以前,你們先看兩張圖,這張圖是整個攔截器的流程,也是OkHttp的精華,設計之巧妙.
從上面的代碼也能夠看到,getResponseWithInterceptorChain方法是獲取到了網絡請求的最終數據的.緊接着根據我畫了兩張圖,這兩張圖主要是描繪了從getResponseWithInterceptorChain進去以後發生的事,它內部會串行的執行一些特定的攔截器(interceptors),每一個攔截器負責一個特殊的職責.最後那個攔截器負責請求服務器,而後服務器返回了數據再根據這個攔截器的順序逆序返回回去,最終就獲得了網絡數據.
下面先簡單介紹一下這些攔截器,方便後面的源碼梳理
有了上面的簡單介紹,咱們直接進入getResponseWithInterceptorChain方法一探究竟.
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
//用來盛放全部的攔截器的
List<Interceptor> interceptors = new ArrayList<>();
//1. 添加用戶定義的攔截器
interceptors.addAll(client.interceptors());
//2. 添加一些OkHttp自帶的攔截器
interceptors.add(new RetryAndFollowUpInterceptor(client));
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
//這裏還有一個網絡攔截器,也是能夠用戶自定義的
interceptors.addAll(client.networkInterceptors());
}
//最終訪問服務器的攔截器
interceptors.add(new CallServerInterceptor(forWebSocket));
//3. 將攔截器,當前攔截器索引等傳入Interceptor.Chain
Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,
originalRequest, this, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
boolean calledNoMoreExchanges = false;
try {
//4. 請求訪問下一個攔截器
Response response = chain.proceed(originalRequest);
if (transmitter.isCanceled()) {
closeQuietly(response);
throw new IOException("Canceled");
}
return response;
} catch (IOException e) {
calledNoMoreExchanges = true;
throw transmitter.noMoreExchanges(e);
} finally {
if (!calledNoMoreExchanges) {
transmitter.noMoreExchanges(null);
}
}
}
複製代碼
能夠看到,OkHttp這個攔截器鏈的大致流程,最開始是用戶自定義的攔截器,而後纔是OkHttp本身默認的攔截器(須要注意的是,最後一個攔截器是CallServerInterceptor).而後將攔截器集合和當前攔截器的索引等數據傳入RealInterceptorChain,調用RealInterceptorChain對象的proceed,並最終獲得執行結果.看來邏輯在RealInterceptorChain的proceed方法內部
public final class RealInterceptorChain implements Interceptor.Chain {
private final List<Interceptor> interceptors;
private final Transmitter transmitter;
private final @Nullable Exchange exchange;
private final int index;
private final Request request;
private final Call call;
private final int connectTimeout;
private final int readTimeout;
private final int writeTimeout;
private int calls;
public RealInterceptorChain(List<Interceptor> interceptors, Transmitter transmitter, @Nullable Exchange exchange, int index, Request request, Call call, int connectTimeout, int readTimeout, int writeTimeout) {
this.interceptors = interceptors;
this.transmitter = transmitter;
this.exchange = exchange;
this.index = index;
this.request = request;
this.call = call;
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
this.writeTimeout = writeTimeout;
}
@Override
public Response proceed(Request request) throws IOException {
return proceed(request, transmitter, exchange);
}
public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange) throws IOException {
calls++;
// Call the next interceptor in the chain.
//調用下一個interceptor.注意到,這裏的index索引+1了的,因此是下一個interceptor
RealInterceptorChain next = new RealInterceptorChain(interceptors, transmitter, exchange,
index + 1, request, call, connectTimeout, readTimeout, writeTimeout);
//當前interceptor
Interceptor interceptor = interceptors.get(index);
//調用interceptor的intercept方法
Response response = interceptor.intercept(next);
return response;
}
}
複製代碼
在proceed方法裏面主要是將下一個攔截器的RealInterceptorChain構建出來,而後傳入當前攔截器的intercept方法裏面,方便在intercept方法裏面執行下一個RealInterceptorChain的proceed方法.intercept方法返回的是獲取數據以後的Response.
下面進入intercept方法內部,Interceptor實際上是一個接口,而後全部的攔截器都實現了這個接口Interceptor.若是沒有用戶自定義的攔截器,那麼第一個攔截器就是RetryAndFollowUpInterceptor
RetryAndFollowUpInterceptor#intercept
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Transmitter transmitter = realChain.transmitter();
int followUpCount = 0;
Response priorResponse = null;
//死循環 直到達到重定向的最大次數
while (true) {
//準備一個流來承載request,若是存在則複用
transmitter.prepareToConnect(request);
if (transmitter.isCanceled()) {
throw new IOException("Canceled");
}
Response response;
boolean success = false;
try {
//調用下一個攔截器
response = realChain.proceed(request, transmitter, null);
success = true;
} catch (RouteException e) {
//下面是一些失敗,而後又從新請求的代碼
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), transmitter, false, request)) {
throw e.getFirstConnectException();
}
continue;
} catch (IOException e) {
// An attempt to communicate with a server failed. The request may have been sent.
boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
if (!recover(e, transmitter, requestSendStarted, request)) throw e;
continue;
} finally {
// The network call threw an exception. Release any resources.
if (!success) {
transmitter.exchangeDoneDueToException();
}
}
// Attach the prior response if it exists. Such responses never have a body.
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
Exchange exchange = Internal.instance.exchange(response);
Route route = exchange != null ? exchange.connection().route() : null;
Request followUp = followUpRequest(response, route);
if (followUp == null) {
if (exchange != null && exchange.isDuplex()) {
transmitter.timeoutEarlyExit();
}
return response;
}
RequestBody followUpBody = followUp.body();
if (followUpBody != null && followUpBody.isOneShot()) {
return response;
}
closeQuietly(response.body());
if (transmitter.hasExchange()) {
exchange.detachWithViolence();
}
if (++followUpCount > MAX_FOLLOW_UPS) {
throw new ProtocolException("Too many follow-up requests: " + followUpCount);
}
request = followUp;
priorResponse = response;
}
}
複製代碼
RetryAndFollowUpInterceptor主要是負責錯誤處理,以及重定向.固然重定向是有最大次數的,OkHttp規定是20次.
RetryAndFollowUpInterceptor執行proceed方法是來到了BridgeInterceptor,它是一個鏈接橋.添加了不少header
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
//進行header的包裝
RequestBody body = userRequest.body();
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) {
requestBuilder.header("Content-Type", contentType.toString());
}
long contentLength = body.contentLength();
if (contentLength != -1) {
requestBuilder.header("Content-Length", Long.toString(contentLength));
requestBuilder.removeHeader("Transfer-Encoding");
} else {
requestBuilder.header("Transfer-Encoding", "chunked");
requestBuilder.removeHeader("Content-Length");
}
}
if (userRequest.header("Host") == null) {
requestBuilder.header("Host", hostHeader(userRequest.url(), false));
}
if (userRequest.header("Connection") == null) {
requestBuilder.header("Connection", "Keep-Alive");
}
//添加Accept-Encoding:gzip
// If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
// the transfer stream.
boolean transparentGzip = false;
if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
transparentGzip = true;
requestBuilder.header("Accept-Encoding", "gzip");
}
//建立OkhttpClient配置的cookieJar
List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", cookieHeader(cookies));
}
if (userRequest.header("User-Agent") == null) {
requestBuilder.header("User-Agent", Version.userAgent());
}
//執行下一個Interceptor
Response networkResponse = chain.proceed(requestBuilder.build());
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
//先判斷服務器是否支持gzip壓縮,支持則交給Okio處理
if (transparentGzip
&& "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
&& HttpHeaders.hasBody(networkResponse)) {
GzipSource responseBody = new GzipSource(networkResponse.body().source());
Headers strippedHeaders = networkResponse.headers().newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build();
responseBuilder.headers(strippedHeaders);
String contentType = networkResponse.header("Content-Type");
responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
}
//最後將結果返回
return responseBuilder.build();
}
複製代碼
BridgeInterceptor就跟它的名字那樣,它是一個鏈接橋.它負責把用戶構造的請求轉換成發送給服務器的請求,就是添加了很多的header,其中還有gzip等.
BridgeInterceptor的下一個攔截器是CacheInterceptor
@Override public Response intercept(Chain chain) throws IOException {
////若是配置了緩存:優先從緩存中讀取Response
Response cacheCandidate = cache != null
? cache.get(chain.request())
: null;
long now = System.currentTimeMillis();
//緩存策略,該策略經過某種規則來判斷緩存是否有效
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;
Response cacheResponse = strategy.cacheResponse;
if (cache != null) {
cache.trackResponse(strategy);
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
// If we're forbidden from using the network and the cache is insufficient, fail.
//若是根據緩存策略strategy禁止使用網絡,而且緩存無效,直接返回空的Response
if (networkRequest == null && cacheResponse == null) {
return new Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(Util.EMPTY_RESPONSE)
.sentRequestAtMillis(-1L)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
}
// If we don't need the network, we're done.
//若是根據緩存策略strategy禁止使用網絡,且有緩存則直接使用緩存
if (networkRequest == null) {
return cacheResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.build();
}
//須要網絡
Response networkResponse = null;
try {
//執行下一個攔截器,發起網路請求
networkResponse = chain.proceed(networkRequest);
} finally {
// If we're crashing on I/O or otherwise, don't leak the cache body.
if (networkResponse == null && cacheCandidate != null) {
closeQuietly(cacheCandidate.body());
}
}
//本地有緩存,
// If we have a cache response too, then we're doing a conditional get.
if (cacheResponse != null) {
//而且服務器返回304狀態碼(說明緩存還沒過時或服務器資源沒修改)
if (networkResponse.code() == HTTP_NOT_MODIFIED) {
//使用緩存數據
Response response = cacheResponse.newBuilder()
.headers(combine(cacheResponse.headers(), networkResponse.headers()))
.sentRequestAtMillis(networkResponse.sentRequestAtMillis())
.receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
// Update the cache after combining headers but before stripping the
// Content-Encoding header (as performed by initContentStream()).
cache.trackConditionalCacheHit();
cache.update(cacheResponse, response);
return response;
} else {
closeQuietly(cacheResponse.body());
}
}
//若是網絡資源已經修改:使用網絡響應返回的最新數據
Response response = networkResponse.newBuilder()
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
//將最新的數據緩存起來
if (cache != null) {
if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
// Offer this request to the cache.
CacheRequest cacheRequest = cache.put(response);
return cacheWritingResponse(cacheRequest, response);
}
if (HttpMethod.invalidatesCache(networkRequest.method())) {
try {
cache.remove(networkRequest);
} catch (IOException ignored) {
// The cache cannot be written.
}
}
}
//返回最新的數據
return response;
}
複製代碼
CacheInterceptor是進行一些緩存上面的處理,接下來是ConnectInterceptor
@Override
public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
Transmitter transmitter = realChain.transmitter();
// We need the network to satisfy this request. Possibly for validating a conditional GET.
//判斷請求是否是GET方法, 不是的狀況下,須要進行有效監測
boolean doExtensiveHealthChecks = !request.method().equals("GET");
Exchange exchange = transmitter.newExchange(chain, doExtensiveHealthChecks);
//執行下一個攔截器
return realChain.proceed(request, transmitter, exchange);
}
複製代碼
ConnectInterceptor的下一個攔截器就是最好一個攔截器CallServerInterceptor了.
@Override public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Exchange exchange = realChain.exchange();
Request request = realChain.request();
long sentRequestMillis = System.currentTimeMillis();
//整理請求頭並寫入
exchange.writeRequestHeaders(request);
boolean responseHeadersStarted = false;
Response.Builder responseBuilder = null;
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
// If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
// Continue" response before transmitting the request body. If we don't get that, return
// what we did get (such as a 4xx response) without ever transmitting the request body.
if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
exchange.flushRequest();
responseHeadersStarted = true;
exchange.responseHeadersStart();
responseBuilder = exchange.readResponseHeaders(true);
}
if (responseBuilder == null) {
if (request.body().isDuplex()) {
// Prepare a duplex body so that the application can send a request body later.
exchange.flushRequest();
BufferedSink bufferedRequestBody = Okio.buffer(
exchange.createRequestBody(request, true));
request.body().writeTo(bufferedRequestBody);
} else {
// Write the request body if the "Expect: 100-continue" expectation was met.
BufferedSink bufferedRequestBody = Okio.buffer(
exchange.createRequestBody(request, false));
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
}
} else {
exchange.noRequestBody();
if (!exchange.connection().isMultiplexed()) {
// If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection
// from being reused. Otherwise we're still obligated to transmit the request body to
// leave the connection in a consistent state.
exchange.noNewExchangesOnConnection();
}
}
} else {
exchange.noRequestBody();
}
if (request.body() == null || !request.body().isDuplex()) {
//發送最終的請求
exchange.finishRequest();
}
if (!responseHeadersStarted) {
exchange.responseHeadersStart();
}
if (responseBuilder == null) {
//響應頭
responseBuilder = exchange.readResponseHeaders(false);
}
Response response = responseBuilder
.request(request)
.handshake(exchange.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
int code = response.code();
if (code == 100) {
// server sent a 100-continue even though we did not request one.
// try again to read the actual response
response = exchange.readResponseHeaders(false)
.request(request)
.handshake(exchange.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
code = response.code();
}
exchange.responseHeadersEnd(response);
if (forWebSocket && code == 101) {
// Connection is upgrading, but we need to ensure interceptors see a non-null response body.
response = response.newBuilder()
.body(Util.EMPTY_RESPONSE)
.build();
} else {
response = response.newBuilder()
.body(exchange.openResponseBody(response))
.build();
}
//斷開鏈接
if ("close".equalsIgnoreCase(response.request().header("Connection"))
|| "close".equalsIgnoreCase(response.header("Connection"))) {
exchange.noNewExchangesOnConnection();
}
//拋出協議異常
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}
複製代碼
這是鏈中最後一個攔截器,它向 服務器 發起了一次網絡訪問.負責向服務器發送請求數據、從服務器讀取響應數據.拿到數據以後再沿着鏈返回.
OkHttp的攔截器鏈設計得很是巧妙,是典型的責任鏈模式.並最終由最後一個鏈處理了網絡請求,並拿到結果.本文主要是對OkHttp主流程進行了梳理,經過本文能對OkHttp有一個總體的瞭解.