文章首發(fā)于掘金-從OKHttp框架看代碼設(shè)計(jì)
在Android端皂吮,比較有名的是OkHttp和Retrofit透葛,后者在網(wǎng)絡(luò)請(qǐng)求又是依賴OkHttp的。所以說(shuō)OkHttp是Android世界里最出名的框架也不為過(guò)颇玷,今天锌云,我們就來(lái)認(rèn)真分析一下這個(gè)框架,依照我務(wù)實(shí)的風(fēng)格褂乍,這篇文章絕對(duì)不會(huì)是為了讀源碼而讀源碼持隧。
HTTP簡(jiǎn)介
分析這個(gè)Http框架,我們就先從Http談起逃片,Http是互聯(lián)網(wǎng)上應(yīng)用最普遍的通訊協(xié)議屡拨。而所謂通訊協(xié)議,就是指通訊雙方約定好傳輸數(shù)據(jù)的格式褥实。所以要理解Http呀狼,只需要理解Http傳輸數(shù)據(jù)的格式,下面是Http數(shù)據(jù)傳輸雙方的大致的數(shù)據(jù)格式性锭。
上圖列出的并不夠詳細(xì)赠潦,因?yàn)槲覀儾⒉皇窍胙芯縃ttp本身。
從上圖可以看到草冈,一個(gè)Http請(qǐng)求本身其實(shí)很簡(jiǎn)單她奥。
從客戶端的角度來(lái)看
- 裝配Request(涉及到請(qǐng)求方法瓮增,url,cookie等等)
- Client端發(fā)送request請(qǐng)求
- 接收服務(wù)端返回的Response數(shù)據(jù)
是不是簡(jiǎn)單到令人發(fā)指哩俭?說(shuō)起來(lái)這和大象裝冰箱其實(shí)還蠻像的绷跑。
一個(gè)簡(jiǎn)單的OkHttp請(qǐng)求
結(jié)合上面的步驟,我們來(lái)看看在OkHttp框架是怎么完成簡(jiǎn)單一個(gè)網(wǎng)絡(luò)請(qǐng)求的呢凡资?
//構(gòu)造Request
Request req=new Request.Builder()
.url(url)
.build();
//構(gòu)造一個(gè)HttpClient
OkHttpClient client=new OkHttpClient();
//發(fā)送請(qǐng)求
client.newCall(req)
.enqueue(new Callback() {
//獲得服務(wù)器返回的Response數(shù)據(jù)
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
}
@Override
public void onFailure(Call arg0, IOException arg1) {
// TODO Auto-generated method stub
}
});
你瞧砸捏,這些步驟和我們預(yù)想的都是一樣的,OKHttp為你封裝了那些復(fù)雜隙赁,繁瑣的東西垦藏,只給你你想要的和你需要的。
既然它把Http請(qǐng)求封裝得如此簡(jiǎn)單伞访,它的內(nèi)部的設(shè)計(jì)是否也非常的嚴(yán)謹(jǐn)呢掂骏?
首先給出OkHttp框架的整個(gè)處理流程:
可以看到,OKHttp的框架中厚掷,構(gòu)造Request和HttpClient兩個(gè)過(guò)程其實(shí)還是很簡(jiǎn)單的弟灼,而發(fā)送請(qǐng)求的過(guò)程則顯得十分復(fù)雜,當(dāng)然也是最精彩的部分冒黑。
下面我們就按照客戶端Http請(qǐng)求的流程來(lái)看看OKHttp框架的源碼田绑。
構(gòu)造Request
public final class Request {
.......
.....
public static class Builder {
private HttpUrl url;
private String method;
private Headers.Builder headers;
private RequestBody body;
private Object tag;
}
}
使用builder的方式,來(lái)插入請(qǐng)求的數(shù)據(jù)抡爹,構(gòu)建Request,Builder模式相信大家非常熟悉了掩驱,所以這里僅僅給出它可構(gòu)造的參數(shù)。
雖然說(shuō)是構(gòu)建Request豁延,其實(shí)也言過(guò)其實(shí)昙篙,因?yàn)槟隳芸吹綄?shí)際上這些數(shù)據(jù)是不足以構(gòu)建一個(gè)合法的Request的,其他待補(bǔ)全的信息其實(shí)是OkHttp在后面某個(gè)環(huán)節(jié)幫你加上去诱咏,但至少,在開發(fā)者來(lái)看缴挖,第一步構(gòu)建Request此時(shí)已經(jīng)完成了袋狞。
構(gòu)造OKHttpClient
public class OkHttpClient implements Cloneable, Call.Factory, WebSocketCall.Factory {
......
......
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;
}
....
....
@Override
public Call newCall(Request request) {
return new RealCall(this, request, false /* for web socket */);
}
....
....
}
依然是Builder來(lái)構(gòu)建OKHttpClient,值得注意的是OKHttpClient實(shí)現(xiàn)了 Call.Factory接口映屋,創(chuàng)建一個(gè)RealCall類的實(shí)例(Call的實(shí)現(xiàn)類)苟鸯。開頭我們看到,在發(fā)送請(qǐng)求之前棚点,需要調(diào)用newCall()方法早处,創(chuàng)建一個(gè)指向RealCall實(shí)現(xiàn)類的Call對(duì)象,實(shí)際上RealCall包裝了Request和OKHttpClient這兩個(gè)類的實(shí)例瘫析。使得后面的方法中可以很方便的使用這兩者砌梆。
我們可以看看RealCall的上層接口Call:
public interface Call extends Cloneable {
Request request();
Response execute() throws IOException;
void enqueue(Callback responseCallback);
void cancel();
boolean isExecuted();
boolean isCanceled();
Call clone();
interface Factory {
Call newCall(Request request);
}
}
基本上我們會(huì)用到的大部分操作都定義在這個(gè)接口里面了默责,可以說(shuō)這個(gè)接口是OkHttp框架的操作核心。在構(gòu)造完HttpClient和Request之后咸包,我們只要持有Call對(duì)象的引用就可以操控請(qǐng)求了桃序。
我們繼續(xù)按照上面的流程圖來(lái)查看代碼,發(fā)送請(qǐng)求時(shí)烂瘫,將請(qǐng)求丟入請(qǐng)求隊(duì)列媒熊,即調(diào)用realCall.enqueue();
RealCall.java
@Override
public void enqueue(Callback responseCallback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
//對(duì)代碼做了一點(diǎn)結(jié)構(gòu)上的轉(zhuǎn)化,幫助閱讀
Dispatcher dispatcher=client.dispatcher()
//從這里我們也能感覺(jué)到坟比,我們應(yīng)該全局維護(hù)一個(gè)OkHttpClient實(shí)例芦鳍,
//因?yàn)槊總€(gè)實(shí)例都會(huì)帶有一個(gè)請(qǐng)求隊(duì)列,而我們只需要一個(gè)請(qǐng)求隊(duì)列即可
dispatcher.enqueue(new AsyncCall(responseCallback));
/*
*這個(gè)AsyncCall類繼承自Runnable
*AsyncCall(responseCallback)相當(dāng)于構(gòu)建了一個(gè)可運(yùn)行的線程
*responseCallback就是我們期望的response的回調(diào)
*/
}
我們可以進(jìn)入Dispatcher這個(gè)分發(fā)器內(nèi)部看看enqueue()方法的細(xì)節(jié)葛账,再回頭看看AsyncCall執(zhí)行的內(nèi)容柠衅。
Dispatcher.java
...
...
/**等待異步執(zhí)行的隊(duì)列 */
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<>();
...
...
synchronized void enqueue(AsyncCall call) {
//如果正在執(zhí)行的請(qǐng)求小于設(shè)定值,
//并且請(qǐng)求同一個(gè)主機(jī)的request小于設(shè)定值
if (runningAsyncCalls.size() < maxRequests &&
runningCallsForHost(call) < maxRequestsPerHost) {
//添加到執(zhí)行隊(duì)列注竿,開始執(zhí)行請(qǐng)求
runningAsyncCalls.add(call);
//獲得當(dāng)前線程池茄茁,沒(méi)有則創(chuàng)建一個(gè)
ExecutorService mExecutorService=executorService();
//執(zhí)行線程
mExecutorService.execute(call);
} else {
//添加到等待隊(duì)列中
readyAsyncCalls.add(call);
}
}
在分發(fā)器中,它會(huì)根據(jù)情況決定把call加入請(qǐng)求隊(duì)列還是等待隊(duì)列巩割,在請(qǐng)求隊(duì)列中的話裙顽,就會(huì)在線程池中執(zhí)行這個(gè)請(qǐng)求。
嗯宣谈,現(xiàn)在我們可以回頭查看AsyncCall這個(gè)Runnable的實(shí)現(xiàn)類
RealCall.java
//它是RealCall的一個(gè)內(nèi)部類
//NamedRunnable實(shí)現(xiàn)了Runnable接口愈犹,把run()方法封裝成了execute()
final class AsyncCall extends NamedRunnable {
private final Callback responseCallback;
AsyncCall(Callback responseCallback) {
super("OkHttp %s", redactedUrl());
this.responseCallback = responseCallback;
}
String host() {
return originalRequest.url().host();
}
Request request() {
return originalRequest;
}
RealCall get() {
return RealCall.this;
}
@Override
protected void execute() {
boolean signalledCallback = false;
try {
//一言不和就返回Response,那沒(méi)說(shuō)的闻丑,這個(gè)方法里面肯定執(zhí)行了request請(qǐng)求
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);
}
}
}
...
...
//顯然請(qǐng)求在這里發(fā)生
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 (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(forWebSocket));
//包裹這request的chain
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
在這個(gè)getResponseWithInterceptorChain()方法中漩怎,我們看到了大量的Interceptor,根據(jù)上面的流程圖嗦嗡,就意味著網(wǎng)絡(luò)請(qǐng)求流程可能到了末尾了勋锤,也終于到了我介紹的重點(diǎn)了,因?yàn)檫@個(gè)Interceptor設(shè)計(jì)確實(shí)是精彩侥祭。
了解Interceptor之前叁执,我們先來(lái)理一理,到目前為止矮冬,我們只有一個(gè)信息不全的Request谈宛,框架也沒(méi)有做什么實(shí)質(zhì)性的工作,與其說(shuō)網(wǎng)絡(luò)請(qǐng)求快到結(jié)尾了胎署,不如說(shuō)我們才剛剛開始吆录,因?yàn)楹芏嗍虑椋?strong>為Request添加必要信息,request失敗重連,緩存琼牧,獲取Response等等這些什么都沒(méi)做恢筝,也就是說(shuō)哀卫,這所有的工作都交給了Interceptor,你能想象這有多復(fù)雜滋恬。聊训。
Interceptor:你們這些辣雞。
Interceptor詳解
Interceptor是攔截者的意思恢氯,就是把Request請(qǐng)求或者Response回復(fù)做一些處理带斑,而OkHttp通過(guò)一個(gè)“鏈條”Chain把所有的Interceptor串聯(lián)在一起,保證所有的Interceptor一個(gè)接著一個(gè)執(zhí)行勋拟。
這個(gè)設(shè)計(jì)突然之間就把問(wèn)題分解了勋磕,在這種機(jī)制下,所有繁雜的事物都可以歸類敢靡,每個(gè)Interceptor只執(zhí)行一小類事物挂滓。這樣,每個(gè)Interceptor只關(guān)注自己份內(nèi)的事物啸胧,問(wèn)題的復(fù)雜度一下子降低了幾倍赶站。而且這種插拔的設(shè)計(jì),極大的提高了程序的可拓展性纺念。
我特么怎么就沒(méi)有想到過(guò)這種設(shè)計(jì)贝椿??
平復(fù)一下心情......
我們先來(lái)看看Interceptor接口:
public interface Interceptor {
//只有一個(gè)接口方法
Response intercept(Chain chain) throws IOException;
//Chain大概是鏈條的意思
interface Chain {
// Chain其實(shí)包裝了一個(gè)Request請(qǐng)求
Request request();
//獲得Response
Response proceed(Request request) throws IOException;
//獲得當(dāng)前網(wǎng)絡(luò)連接
Connection connection();
}
}
其實(shí)“鏈條”這個(gè)概念不是很容易理解Interceptor(攔截者),因此陷谱,我用一個(gè)更加生動(dòng)的環(huán)形流水線生產(chǎn)的例子來(lái)幫助你在概念上完全理解Interceptor烙博。
“包裝了Request的Chain遞歸的從每個(gè)Interceptor手中走過(guò)去,最后請(qǐng)求網(wǎng)絡(luò)得到的Response又會(huì)逆序的從每個(gè)Interceptor走回來(lái)烟逊,把Response返回到開發(fā)者手中”
我相信渣窜,通過(guò)這個(gè)例子,關(guān)于OkHttp的Interceptor以及它和Chain之間的關(guān)系在概念上應(yīng)該能夠理清楚了宪躯。
但是我仍然想講講每個(gè)Intercept的作用乔宿,以及在代碼層面他們是如何依次被調(diào)用的。
那我們繼續(xù)看看代碼
Response getResponseWithInterceptorChain() throws IOException {
List<Interceptor> interceptors = new ArrayList<>();
//添加開發(fā)者應(yīng)用層自定義的Interceptor
interceptors.addAll(client.interceptors());
//這個(gè)Interceptor是處理請(qǐng)求失敗的重試访雪,重定向
interceptors.add(retryAndFollowUpInterceptor);
//這個(gè)Interceptor工作是添加一些請(qǐng)求的頭部或其他信息
//并對(duì)返回的Response做一些友好的處理(有一些信息你可能并不需要)
interceptors.add(new BridgeInterceptor(client.cookieJar()));
//這個(gè)Interceptor的職責(zé)是判斷緩存是否存在予颤,讀取緩存,更新緩存等等
interceptors.add(new CacheInterceptor(client.internalCache()));
//這個(gè)Interceptor的職責(zé)是建立客戶端和服務(wù)器的連接
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
//添加開發(fā)者自定義的網(wǎng)絡(luò)層攔截器
interceptors.addAll(client.networkInterceptors());
}
//這個(gè)Interceptor的職責(zé)是向服務(wù)器發(fā)送數(shù)據(jù)冬阳,
//并且接收服務(wù)器返回的Response
interceptors.add(new CallServerInterceptor(forWebSocket));
//一個(gè)包裹這request的chain
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
//把chain傳遞到第一個(gè)Interceptor手中
return chain.proceed(originalRequest);
}
到這里,我們通過(guò)源碼已經(jīng)可以總結(jié)一些在開發(fā)中需要注意的問(wèn)題了:
- Interceptor的執(zhí)行的是順序的党饮,也就意味著當(dāng)我們自己自定義Interceptor時(shí)是否應(yīng)該注意添加的順序呢肝陪?
- 在開發(fā)者自定義攔截器時(shí),是有兩種不同的攔截器可以自定義的刑顺。
接著氯窍,從上面最后兩行代碼講起:
首先創(chuàng)建了一個(gè)指向RealInterceptorChain這個(gè)實(shí)現(xiàn)類的chain引用饲常,然后調(diào)用了 proceed(request)方法。
RealInterceptorChain.java
public final class RealInterceptorChain implements Interceptor.Chain {
private final List<Interceptor> interceptors;
private final StreamAllocation streamAllocation;
private final HttpCodec httpCodec;
private final Connection connection;
private final int index;
private final Request request;
private int calls;
public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
HttpCodec httpCodec, Connection connection, int index, Request request) {
this.interceptors = interceptors;
this.connection = connection;
this.streamAllocation = streamAllocation;
this.httpCodec = httpCodec;
this.index = index;
this.request = request;
}
....
....
....
@Override
public Response proceed(Request request) throws IOException {
//直接調(diào)用了下面的proceed(.....)方法狼讨。
return proceed(request, streamAllocation, httpCodec, connection);
}
//這個(gè)方法用來(lái)獲取list中下一個(gè)Interceptor贝淤,并調(diào)用它的intercept()方法
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
Connection connection) throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
calls++;
....
....
....
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request);
//從list中獲取到第一個(gè)Interceptor
Interceptor interceptor = interceptors.get(index);
//然后調(diào)用這個(gè)Interceptor的intercept()方法,并等待返回Response
Response response = interceptor.intercept(next);
....
....
return response;
}
從上文可知政供,如果沒(méi)有開發(fā)者自定義的Interceptor時(shí)播聪,首先調(diào)用的RetryAndFollowUpInterceptor,負(fù)責(zé)失敗重連操作
RetryAndFollowUpInterceptor.java
...
...
//直接調(diào)用自身的intercept()方法
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
....
....
Response response = null;
boolean releaseConnection = true;
try {
//在這里通過(guò)繼續(xù)調(diào)用RealInterceptorChain.proceed()這個(gè)方法
//在RealInterceptorChain的list中拿到下一個(gè)Interceptor
//然后繼續(xù)調(diào)用Interceptor.intercept()布隔,并等待返回Response
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
releaseConnection = false;
} catch (RouteException e) {
....
....
} catch (IOException e) {
....
....
} finally {
....
....
}
}
}
...
...
嗯离陶,到這里,Interceptor才算講的差不多了衅檀,OKHttp也才算講得差不多了招刨,如果你想研究每個(gè)Interceptor的細(xì)節(jié),歡迎自行閱讀源碼哀军,現(xiàn)在在框架上沉眶,你不會(huì)再遇到什么難題了。這里篇幅太長(zhǎng)杉适,不能再繼續(xù)講了谎倔。
如果你還是好奇OKHttp到底是怎么發(fā)出請(qǐng)求?
我可以做一點(diǎn)簡(jiǎn)短的介紹:這個(gè)請(qǐng)求動(dòng)作發(fā)生在CallServerInterceptor(也就是最后一個(gè)Interceptor)中淘衙,而且其中還涉及到Okio這個(gè)io框架传藏,通過(guò)Okio封裝了流的讀寫操作,可以更加方便彤守,快速的訪問(wèn)毯侦、存儲(chǔ)和處理數(shù)據(jù)。最終請(qǐng)求調(diào)用到了socket這個(gè)層次,然后獲得Response具垫。
總結(jié)
OKHttp中的這個(gè)Interceptor這個(gè)設(shè)計(jì)十分精彩侈离,不僅分解了問(wèn)題,降低了復(fù)雜度筝蚕,還提高了拓展性卦碾,和可維護(hù)性,總之值得大家認(rèn)真學(xué)習(xí)起宽。
我記得有位前輩和我講過(guò)洲胖,好的工程師不是代碼寫的快寫的工整,而是代碼的設(shè)計(jì)完美坯沪。很多時(shí)候绿映,我們都在埋頭寫代碼,卻忘記了如何設(shè)計(jì)代碼,如何在代碼層面有效的分解難度叉弦,劃分問(wèn)題丐一,即使在增加需求,項(xiàng)目的復(fù)雜度也保持不變淹冰,這是我們都應(yīng)該思考的問(wèn)題库车。
所有牛逼的工程師,都是一個(gè)牛逼的設(shè)計(jì)師樱拴。
共勉柠衍。
勘誤
暫無(wú)