寫(xiě)在前面
作為一名android開(kāi)發(fā)者迫吐,要時(shí)時(shí)刻刻跟隨技術(shù)的發(fā)展潮流宰缤,OKHttp作為當(dāng)下最流行的網(wǎng)絡(luò)請(qǐng)求框架我們不得不重視痊剖,它的原理也幾乎是面試時(shí)必問(wèn)的問(wèn)題告丢,故而對(duì)其進(jìn)行學(xué)習(xí)并紀(jì)錄之枪蘑。
幾個(gè)類
- OKHttpClient
okhttp3在項(xiàng)目中發(fā)起請(qǐng)求的代碼如下:
okHttpClient.newCall(request).execute();
OKHttpClient 類中組合了很多的類對(duì)象,并且繼承了Call.Factory岖免,提供的方法只有一個(gè):newCall岳颇,返回的是一個(gè)Call對(duì)象(實(shí)際是RealCall是Call的實(shí)現(xiàn)類)。
@Override
public Call newCall(Request request) {
return new RealCall(this, request);
}
使用okHttpClient最好創(chuàng)建一個(gè)單例颅湘,因?yàn)槊恳粋€(gè)client都有自己的一個(gè)連接池connection pool和線程池thread pools话侧。重用這些連接池和線程池可以減少延遲和節(jié)約內(nèi)存。
okHttpClient使用了builder模式
public static final class Builder {
Dispatcher dispatcher;
Proxy proxy;
List<Protocol> protocols;
List<ConnectionSpec> connectionSpecs;
final List<Interceptor> interceptors = new ArrayList<>();
final List<Interceptor> networkInterceptors = new ArrayList<>();
ProxySelector proxySelector;
CookieJar cookieJar;
Cache cache;
InternalCache internalCache;
SocketFactory socketFactory;
SSLSocketFactory sslSocketFactory;
CertificateChainCleaner certificateChainCleaner;
HostnameVerifier hostnameVerifier;
CertificatePinner certificatePinner;
Authenticator proxyAuthenticator;
Authenticator authenticator;
ConnectionPool connectionPool;
Dns dns;
boolean followSslRedirects;
boolean followRedirects;
boolean retryOnConnectionFailure;
int connectTimeout;
int readTimeout;
int writeTimeout;
...
}
可以看到OKHttpClient中包含的所有字段闯参。
- Dispatcher
Dispatcher我們可以理解為一個(gè)執(zhí)行策略(官方這樣說(shuō)的:Policy on when async requests are executed.)瞻鹏,當(dāng)我們調(diào)用newCall時(shí)悲立,它不斷的從RequestQueue中取出請(qǐng)求(Call),該引擎有同步和異步請(qǐng)求新博,同步請(qǐng)求通過(guò)Call.execute()直接返 回當(dāng)前的Response薪夕,而異步請(qǐng)求會(huì)把當(dāng)前的請(qǐng)求Call.enqueue添加(AsyncCall)到請(qǐng)求隊(duì)列中,并通過(guò)回調(diào)(Callback) 的方式來(lái)獲取最后結(jié)果赫悄。
synchronized void executed(RealCall call) {
runningSyncCalls.add(call);
}
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
注意到原献,這里enqueue方法中有一個(gè)判斷:如果當(dāng)前運(yùn)行的異步請(qǐng)求隊(duì)列長(zhǎng)度小于最大請(qǐng)求數(shù),也就是64,并且主機(jī)的請(qǐng)求數(shù)小于每個(gè)主機(jī)的請(qǐng)求數(shù)也就是5,則把當(dāng)前請(qǐng)求添加到 運(yùn)行隊(duì)列埂淮,接著交給線程池ExecutorService處理姑隅,否則則放置到readAsyncCall進(jìn)行緩存,等待執(zhí)行倔撞。
- Call
public interface Call {
Request request();
Response execute() throws IOException;
void enqueue(Callback responseCallback);
void cancel();
boolean isExecuted();
boolean isCanceled();
interface Factory {
Call newCall(Request request);
}
}
Call是一個(gè)接口類讲仰,定義了Http請(qǐng)求的方法,并提供了一個(gè)內(nèi)部接口Factory痪蝇,OkHttpClient即實(shí)現(xiàn)了該接口叮盘。
- RealCall
RealCall是Call的實(shí)現(xiàn)類,里面最主要的兩個(gè)方法是execute和enqueue霹俺。
final class RealCall implements Call {
...
@Override
public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
try {
client.dispatcher().executed(this);
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} finally {
client.dispatcher().finished(this);
}
}
...
@Override
public void enqueue(Callback responseCallback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
...
}
可以看到該類中的execute和enqueue都調(diào)用了dispatcher中的executed和enqueue(代碼前面已貼)柔吼。
上面的代碼中也可以解釋我們前面所說(shuō)的:“同步請(qǐng)求通過(guò)Call.execute()直接返 回當(dāng)前的Response,而異步請(qǐng)求會(huì)把當(dāng)前的請(qǐng)求Call.enqueue添加(AsyncCall)到請(qǐng)求隊(duì)列中丙唧,并通過(guò)回調(diào)(Callback) 的方式來(lái)獲取最后結(jié)果愈魏。”
execute通過(guò)getResponseWithInterceptorChain獲取返回Response想际。
同步方法上面的代碼已經(jīng)足夠了培漏, 這里重點(diǎn)說(shuō)一下異步請(qǐng)求如何獲得返回的結(jié)果:
再回到Dispatcher類,enqueue異步方法中執(zhí)行了executorService().execute(call)胡本,executorService()代碼如下:
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;
}
可以看到上面的代碼中用到了線程池牌柄,這也就意味著后半句的executor(call)必然涉及到了多線程的問(wèn)題,我們來(lái)看代碼:
public interface Executor {
void execute(Runnable command);
}
可以看到execute的參數(shù)是一個(gè)Runnable侧甫,這也意味著AsyncCall必然是一個(gè)Runnable的子類珊佣。下面來(lái)看AsyncCall的源碼:
- AsyncCall
final class AsyncCall extends NamedRunnable {
private final Callback responseCallback;
private AsyncCall(Callback responseCallback) {
super("OkHttp %s", redactedUrl().toString());
this.responseCallback = responseCallback;
}
...
@Override protected void execute() {
boolean signalledCallback = false;
try {
Response response = getResponseWithInterceptorChain();
if (retryAndFollowUpInterceptor.isCanceled()) {
signalledCallback = true;
responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
signalledCallback = true;
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);
}
}
}
...
}
從上面的代碼中我們可以看到AysncCall繼承自NamedRunnable抽象類,并且會(huì)執(zhí)行execute方法披粟,而execute方法中我們又看到了熟悉的代碼:
Response response = getResponseWithInterceptorChain();
可見(jiàn)返回結(jié)果也是通過(guò)調(diào)用這個(gè)方法得到的咒锻,只不過(guò)與同步相比中間增加了一些過(guò)程,并且請(qǐng)求結(jié)果是通過(guò)responseCallBack返回守屉。
我們來(lái)看一下這個(gè)方法的代碼:
private Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(retryAndFollowUpInterceptor);
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!retryAndFollowUpInterceptor.isForWebSocket()) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(
retryAndFollowUpInterceptor.isForWebSocket()));
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
可以看到惑艇,這個(gè)方法中主要是用到了Interceptor類。
- Interceptor
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
interface Chain {
Request request();
Response proceed(Request request) throws IOException;
Connection connection();
}
}
Interceptor接口代碼很少,但是滨巴;卻是okhttp中非常核心的類思灌,它把實(shí)際的網(wǎng)絡(luò)請(qǐng)求、緩存恭取、透明壓縮等功能都統(tǒng)一了起來(lái)泰偿,每一個(gè)功能都是一個(gè)Interceptor,它們?cè)龠B成一個(gè)Interceptor.Chain秽荤,環(huán)環(huán)相扣,完成一次網(wǎng)絡(luò)請(qǐng)求柠横。
分析getResponseWithInterceptorChain()方法中用到的interceptor:
1窃款,通過(guò)client設(shè)置的interceptors(即builder.addInterceptor())
2,RetryAndFollowUpInterceptor牍氛,負(fù)責(zé)重試和重定向
3晨继,BridgeInterceptor,首先將應(yīng)用層的數(shù)據(jù)類型轉(zhuǎn)換為網(wǎng)絡(luò)調(diào)用層的數(shù)據(jù)類型搬俊,然后將網(wǎng)絡(luò)層返回的數(shù)據(jù)類型轉(zhuǎn)換為應(yīng)用層的數(shù)據(jù)類型
4紊扬,CacheInterceptor,負(fù)責(zé)讀取緩存唉擂,更新緩存
5餐屎,ConnectInterceptor,負(fù)責(zé)和服務(wù)器建立起鏈接
6玩祟,networkInterceptors腹缩,client設(shè)置的networkInterceptor
7,CallServerInterceptor空扎,負(fù)責(zé)向服務(wù)器發(fā)送請(qǐng)求數(shù)據(jù)藏鹊、從服務(wù)器讀取響應(yīng)數(shù)據(jù)
最后一個(gè)interceptor是負(fù)責(zé)跟服務(wù)器通訊的,其他的interceptor配置都要在此之前转锈。
@Override public Response intercept(Chain chain) throws IOException {
HttpStream httpStream = ((RealInterceptorChain) chain).httpStream();
StreamAllocation streamAllocation = ((RealInterceptorChain) chain).streamAllocation();
Request request = chain.request();
long sentRequestMillis = System.currentTimeMillis();
httpStream.writeRequestHeaders(request);
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
Sink requestBodyOut = httpStream.createRequestBody(request, request.body().contentLength());
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
}
httpStream.finishRequest();
Response response = httpStream.readResponseHeaders()
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
if (!forWebSocket || response.code() != 101) {
response = response.newBuilder()
.body(httpStream.openResponseBody(response))
.build();
}
...
return response;
}