フローチャートokhttp
1.初期化を行うokhttpClient
2.新しいCallオブジェクトを作成し、
Call call = client.newCall(request);
public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
@Override
public Call newCall(Request request) {
return new RealCall(this, request, false /* for web socket */);
}
}
RealCallはRealCallのインスタンスを作成するCall.Factoryインタフェースを実現しました
final class RealCall implements Call {
@Override
public void enqueue(Callback responseCallback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
}
1)コールが実行されたかどうかを確認するために、各コールはあなたが完全に別のコールをしたい場合は、コール#クローン法を用いてクローニングすることができ、一度に実行することができます。
2)実際に実行するclient.dispatcher()。エンキュー(本)を使用し
3)AsyncCallはRealCallのサブクラスであります
final class AsyncCall extends NamedRunnable {
private final Callback responseCallback;
AsyncCall(Callback responseCallback) {
super("OkHttp %s", redactedUrl());
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) {
......
responseCallback.onFailure(RealCall.this, e);
} finally {
client.dispatcher().finished(this);
}
}
AsyncCallは継承されたNamedRunnableがexecuteメソッドを実装し、それが失敗した場合に第1の方法は成功しonReponse取得、その後、応答を取得するgetResponseWithInterceptorChain()メソッドを呼び出し、それがONFAILUREコールバックメソッドを呼び出し、コールバックを呼び出します。最後に、ディスパッチャの完成メソッドを呼び出します。
public abstract class NamedRunnable implements Runnable {
......
@Override
public final void run() {
......
try {
execute();
}
......
}
protected abstract void execute();
}
我々はNamedRunnableがRunnbaleインタフェースを実現参照NamedRunnableタスクであることを意味実行方法で起動され、)(抽象クラスは、抽象メソッドが実行され、そのサブクラスは、実行達成AsyncCallでき方法
ディスパッチャ(スケジューラ)の紹介
public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(
//corePoolSize 最小并发线程数,如果是0的话,空闲一段时间后所有线程将全部被销毁
0,
//maximumPoolSize: 最大线程数,当任务进来时可以扩充的线程最大值,当大于了这个值就会根据丢弃处理机制来处理
Integer.MAX_VALUE,
//keepAliveTime: 当线程数大于corePoolSize时,多余的空闲线程的最大存活时间
60,
//单位秒
TimeUnit.SECONDS,
//工作队列,先进先出
new SynchronousQueue<Runnable>(),
//单个线程的工厂
Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
OkHttp、我々は、単一のスレッド・プールの例ExecutorServiceのように構成されました:
Okhttpでは[0は、Integer.MAX_VALUE]スレッドプールのためのコアを構築し、それはスレッドがわずか60秒のために生きるアイドル状態のときに、任意の時点で複数のスレッドを作成するスレッドの任意の最小数を保持していない、それは使用しています「OkHttpディスパッチャ」スレッドファクトリと呼ばれ、作業キューの記憶素子をブロックしていません
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
コールrealCallは即座に実行し、runningAsyncCallsに参加し、同時要求の現在の実装を参照するか、または他のreadyAsyncCallsキューに参加することができます。
同期要求に対して、ディスパッチャは同期タスクを保存するためにある両端キューを使用して、非同期要求のために、ディスパッチャが使用する2両端キューが、要求は、要求が実行されている保存し、保存し、実行する準備ができています
1.ファイル名を指定して実行キューはすぐに非同期で実行します
2. FIFOバッファキューの順序
//Dispatcher的finished函数
void finished(AsyncCall call) {
finished(runningAsyncCalls, call, true);
}
private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
int runningCallsCount;
Runnable idleCallback;
synchronized (this) {
if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
if (promoteCalls) promoteCalls();
runningCallsCount = runningCallsCount();
idleCallback = this.idleCallback;
}
if (runningCallsCount == 0 && idleCallback != null) {
idleCallback.run();
}
}
//打开源码,发现它将正在运行的任务Call从队列runningAsyncCalls中移除后,获取运行数量判断是否进入了Idle状态,接着执行promoteCalls()函数,下面是promoteCalls()方法
private void promoteCalls() {
if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.
for (Iterator<AsyncCall> 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; // Reached max capacity.
}
}
インターセプタチェーン
RealCallは、方法を実行するようなコードを持っている:応答結果= getResponseWithInterceptorChain()。
フローチャート:最初のカスタムインターセプタ
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));
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
return chain.proceed(originalRequest);
RealInterceptorChainを与えたretryAndFollowUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor、networkInterceptors、CallServerInterceptorは、我々はユーザー定義のインターセプターを追加するターン、この方法で見られる、とブロッカーを渡すことができます。その理由は、ターンコールインターセプタで、その後、最終的には前のポストからの応答を返すことが、我々は法進むに依存しているRealInterceptorChain
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
if (index >= interceptors.size()) throw new AssertionError();
......
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
......
return response;
インターセプト現在の方法の傍受を実行し、次の(インデックス+ 1)インターセプタを呼び出します。次の(インデックス+ 1)現在のインターセプタインターセプト法インターセプトに依存するコールは、コールがRealInterceptorChainの方法を続行します
インターセプターとフォローを再試行
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();//获取Request对象
RealInterceptorChain realChain = (RealInterceptorChain) chain;//获取拦截器链对象,用于后面的chain.proceed(...)方法
Call call = realChain.call();
EventListener eventListener = realChain.eventListener();//监听器
streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
call, eventListener, callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {//循环
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
response = realChain.proceed(request, streamAllocation, null, null);//调用下一个拦截器
releaseConnection = false;
} catch (RouteException e) {
// The attempt to connect via a route failed. The request will not have been sent.
if (!recover(e.getLastConnectException(), false, request)) {//路由异常,尝试恢复,如果再失败就抛出异常
throw e.getLastConnectException();
}
releaseConnection = false;
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, requestSendStarted, request)) throw e;连接关闭异常,尝试恢复
releaseConnection = false;
continue;//继续重试
} finally {
// We're throwing an unchecked exception. Release any resources.
if (releaseConnection) {
streamAllocation.streamFailed(null);
streamAllocation.release();
}
}
// Attach the prior response if it exists. Such responses never have a body.
if (priorResponse != null) {//前一个重试得到的Response
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
//Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
//either add authentication headers, follow redirects or handle a client request timeout. If a
//follow-up is either unnecessary or not applicable, this returns null.
// followUpRequest方法的主要作用就是为新的重试Request添加验证头等内容
Request followUp = followUpRequest(response);
if (followUp == null) {//如果一个请求得到的响应code是200,则followUp是为null的。
if (!forWebSocket) { streamAllocation.release(); } return response; }
closeQuietly(response.body());
//-------------------------------异常处理---------------------------------------------
// if (++followUpCount > MAX_FOLLOW_UPS) {//超过最大的次数,抛出异常
streamAllocation.release();
throw new ProtocolException("Too many follow-up requests: " + followUpCount); }
if (followUp.body() instanceof UnrepeatableRequestBody) {
streamAllocation.release();
} throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
} if (!sameConnection(response, followUp.url())) {
streamAllocation.release();
streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(followUp.url()), call, eventListener, callStackTrace);
} else if (streamAllocation.codec() != null) {
throw new IllegalStateException("Closing the body of " + response + " didn't close its backing stream. Bad interceptor?");
}
//--------------------------------------------------------------------------------
request = followUp;//得到处理之后的Request,以用来继续请求,在哪继续请求?肯定还是沿着拦截器链继续搞呗
priorResponse = response;//由priorResponse持有
}
}
}
インターセプタの主な役割は、再試行とフォローあり
要求は様々な理由で失敗し、ルーティング又は接続失敗する場合、回復が試みられ、そうでなければ、レスポンスコード(にResponseCode)は、フォローメソッド要求が新しい要求を取得するために再処理され、次いで、インターセプタチェーン新しい要求を続けます。もちろん、にResponseCodeは、プロセスが終わった200語である場合、
BridgeInterceptor
BridgeInterceptor主な役割は、リクエストヘッダリクエスト(要求前に)、最初の応答に応じて添加した(前処置)を追加することです。ソースを見て:
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
//----------------------request----------------------------------------------
RequestBody body = userRequest.body();
if (body != null) {
MediaType contentType = body.contentType();
if (contentType != null) {//添加Content-Type请求头
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");
}
// 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");
}
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());
}
Response networkResponse = chain.proceed(requestBuilder.build());
//----------------------------------response----------------------------------------------
HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());//保存cookie
Response.Builder responseBuilder = networkResponse.newBuilder()
.request(userRequest);
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")//Content-Encoding、Content-Length不能用于Gzip解压缩
.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();
}
CacheInterceptor
サーバは要求を受信すると、それが戻って200 OKのLast-ModifiedとETagのヘッダ(サーバがキャッシュをサポートしている場合、ああ、二つのヘッドを持つことになります)内のリソースを送信します、リソースがクライアントキャッシュに保存されており、この記録されました二つの特性。クライアントが同じリクエストを送信する必要がある場合の有効期限が切れた場合、日付+キャッシュ制御キャッシュの有効期限が切れたかどうかに応じて判断し、それが運ぶと変更 - 開始リクエストで2 If-None-Matchヘッダ。二つのヘッドの値は、頭部への応答でのLast-Modified値とETagのです。ローカルリソースを介して2つのヘッドサーバーの分析が変更されていない、クライアントが再度ダウンロードする必要はありません応答304を返します。
CacheStrategyキャッシング戦略はCacheInterceptorがキャッシュまたはネットワーク要求の使用を使用している告げるクラスです。
キャッシュは、キャッシュの実際の動作をカプセル化しています。
DiskLruCache:キャッシュベースDiskLruCache。
@Override public Response intercept(Chain chain) throws IOException {
Response cacheCandidate = cache != null
? cache.get(chain.request())//以request的url而来key,获取缓存
: null;
long now = System.currentTimeMillis();
//缓存策略类,该类决定了是使用缓存还是进行网络请求
CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
Request networkRequest = strategy.networkRequest;//网络请求,如果为null就代表不用进行网络请求
Response cacheResponse = strategy.cacheResponse;//缓存响应,如果为null,则代表不使用缓存
if (cache != null) {//根据缓存策略,更新统计指标:请求次数、使用网络请求次数、使用缓存次数
cache.trackResponse(strategy);
}
//缓存不可用,关闭
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
}
//如果既无网络请求可用,又没有缓存,则返回504错误
// If we're forbidden from using the network and the cache is insufficient, fail.
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.缓存可用,直接返回缓存
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());
}
}
//HTTP_NOT_MODIFIED缓存有效,合并网络请求和缓存
// If we have a cache response too, then we're doing a conditional get.
if (cacheResponse != null) {
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;
}
結果キャッシュ・ポリシー・クラスによって返される:
ネットワークが利用されず、キャッシュ有効であれば、1エラーが504返され、
ネットワーク要求、継続しない場合は、図2に示すように、キャッシュは直接使用され、
図3に示すように、所望のネットワークが利用可能である場合、引き続き、ネットワーク要求、
4、キャッシュがある場合は、継続し、ネットワーク要求はHTTP_NOT_MODIFIEDを返すは、キャッシュが有効である説明、およびネットワーク応答バッファ組み合わされた結果。同時に、キャッシュを更新する;
5、継続して、キャッシュなしならば、新しいキャッシュを書き込みます。
私たちは見ることができ、CacheStrategyはCacheInterceptorで重要な役割を果たしました。このクラスは、ネットワーク要求であるか、キャッシュを使用することを決定しました。このクラスのキーコードはgetCandidate()メソッドです。
private CacheStrategy getCandidate() {
// No cached response.
if (cacheResponse == null) {//没有缓存,直接网络请求
return new CacheStrategy(request, null);
}
// Drop the cached response if it's missing a required handshake.
if (request.isHttps() && cacheResponse.handshake() == null) {//https,但没有握手,直接网络请求
return new CacheStrategy(request, null);
}
// If this response shouldn't have been stored, it should never be used
// as a response source. This check should be redundant as long as the
// persistence store is well-behaved and the rules are constant.
if (!isCacheable(cacheResponse, request)) {//不可缓存,直接网络请求
return new CacheStrategy(request, null);
}
CacheControl requestCaching = request.cacheControl();
if (requestCaching.noCache() || hasConditions(request)) {
//请求头nocache或者请求头包含If-Modified-Since或者If-None-Match
//请求头包含If-Modified-Since或者If-None-Match意味着本地缓存过期,需要服务器验证
//本地缓存是不是还能继续使用
return new CacheStrategy(request, null);
}
CacheControl responseCaching = cacheResponse.cacheControl();
if (responseCaching.immutable()) {//强制使用缓存
return new CacheStrategy(null, cacheResponse);
}
long ageMillis = cacheResponseAge();
long freshMillis = computeFreshnessLifetime();
if (requestCaching.maxAgeSeconds() != -1) {
freshMillis = Math.min(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds()));
}
long minFreshMillis = 0;
if (requestCaching.minFreshSeconds() != -1) {
minFreshMillis = SECONDS.toMillis(requestCaching.minFreshSeconds());
}
long maxStaleMillis = 0;
if (!responseCaching.mustRevalidate() && requestCaching.maxStaleSeconds() != -1) {
maxStaleMillis = SECONDS.toMillis(requestCaching.maxStaleSeconds());
}
//可缓存,并且ageMillis + minFreshMillis < freshMillis + maxStaleMillis
// (意味着虽过期,但可用,只是会在响应头添加warning)
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
Response.Builder builder = cacheResponse.newBuilder();
if (ageMillis + minFreshMillis >= freshMillis) {
builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\"");
}
long oneDayMillis = 24 * 60 * 60 * 1000L;
if (ageMillis > oneDayMillis && isFreshnessLifetimeHeuristic()) {
builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
}
return new CacheStrategy(null, builder.build());//使用缓存
}
// Find a condition to add to the request. If the condition is satisfied, the response body
// will not be transmitted.
String conditionName;
String conditionValue;
//流程走到这,说明缓存已经过期了
//添加请求头:If-Modified-Since或者If-None-Match
//etag与If-None-Match配合使用
//lastModified与If-Modified-Since配合使用
//前者和后者的值是相同的
//区别在于前者是响应头,后者是请求头。
//后者用于服务器进行资源比对,看看是资源是否改变了。
// 如果没有,则本地的资源虽过期还是可以用的
if (etag != null) {
conditionName = "If-None-Match";
conditionValue = etag;
} else if (lastModified != null) {
conditionName = "If-Modified-Since";
conditionValue = lastModifiedString;
} else if (servedDate != null) {
conditionName = "If-Modified-Since";
conditionValue = servedDateString;
} else {
return new CacheStrategy(request, null); // No condition! Make a regular request.
}
Headers.Builder conditionalRequestHeaders = request.headers().newBuilder();
Internal.instance.addLenient(conditionalRequestHeaders, conditionName, conditionValue);
Request conditionalRequest = request.newBuilder()
.headers(conditionalRequestHeaders.build())
.build();
return new CacheStrategy(conditionalRequest, cacheResponse);
}
一般的なプロセスは以下のようではない:(関係のif-else AH)
1、なしキャッシュ、直接ネットワーク要求;
2、HTTPSであれば、ない握手、直接ネットワーク要求;
3、キャッシュ不可、直接ネットワーク要求、
4、要求ヘッダーがnocacheキーワードまたは;要求ヘッダーが変更した場合-ので含まなし、一致する場合、又は、サーバがローカル・キャッシュは、直接ネットワークリクエストを使用し続けることができないであることを確認する必要がある
<freshMillis + maxStaleMillis(ただし期限切れ手段5キャッシュ可能、及びageMillis + minFreshMillis 、のみ)最初の警告に応答して追加することができ、キャッシュの使用;
6、キャッシュは、ヘッダを追加する要求を満了した:変更した場合-ため場合、または、なしマッチ、ネットワーク要求。
ConnectInterceptor(コア、接続プール)
未完成の補充の後ろ