亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android OKHttp框架的分發(fā)器與攔截器源碼刨析

 更新時(shí)間:2022年11月21日 16:04:46   作者:lpf_wei  
okhttp是一個(gè)第三方類庫,用于android中請(qǐng)求網(wǎng)絡(luò)。這是一個(gè)開源項(xiàng)目,是安卓端最火熱的輕量級(jí)框架,由移動(dòng)支付Square公司貢獻(xiàn)(該公司還貢獻(xiàn)了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient

1.OKHttp簡單使用

OkHttpClient okHttpClient=new OkHttpClient.Builder().build();
Request request=new Request.Builder()
        .url("http://www.baidu.com")
        .get().build();
Call call = okHttpClient.newCall(request);
try {
    Response execute = call.execute();
    Log.d("lpf","execute"+execute.body());
} catch (IOException e) {
    e.printStackTrace();
}

這樣就使用OkHttp做了一次網(wǎng)絡(luò)請(qǐng)求,使用流程:

  • 通過建造者的方式創(chuàng)建OkHttpClient
  • 通過建造者的方式創(chuàng)建Request
  • 調(diào)用OkHttpClient的newCall方法將Request對(duì)象當(dāng)做參數(shù)傳進(jìn)去創(chuàng)建一個(gè)Call對(duì)象
  • 調(diào)用call的execute(這個(gè)是同步的方式)方法就完成了一次網(wǎng)絡(luò)請(qǐng)求,如果調(diào)用enqueue方法就是進(jìn)行的一步請(qǐng)求。

2.OkHttp分發(fā)器源碼解析

2.1.同步請(qǐng)求方式

public Response execute() throws IOException {
    synchronized (this) {
        if (executed) throw new IllegalStateException("Already Executed");
        executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    try {
        client.dispatcher().executed(this);
        // 發(fā)起請(qǐng)求
        Response result = getResponseWithInterceptorChain();
        if (result == null) throw new IOException("Canceled");
        return result;
    } catch (IOException e) {
        eventListener.callFailed(this, e);
        throw e;
    } finally {
        client.dispatcher().finished(this);
    }
}

同步請(qǐng)求的方式很簡單,就是通過調(diào)用dispatcher分發(fā)器的executed方法,將請(qǐng)求call放到同步請(qǐng)求隊(duì)列runningSyncCalls中,然后執(zhí)行g(shù)etResponseWithInterceptorChain,經(jīng)過各個(gè)攔截器的處理就能拿到請(qǐng)求結(jié)果,然后進(jìn)行返回就好。

這里用到來了runningSyncCalls同步請(qǐng)求隊(duì)列,異步的時(shí)候也會(huì)有隊(duì)列可以做比對(duì)。

2.2.異步的方式進(jìn)行請(qǐng)求

public void enqueue(Callback responseCallback) {
    synchronized (this) { //不能沖突調(diào)用
        if (executed) throw new IllegalStateException("Already Executed");
        executed = true;
    }
    captureCallStackTrace();
    eventListener.callStart(this);
    client.dispatcher().enqueue(new AsyncCall(responseCallback)); //OkHttp會(huì)提供默認(rèn)的分發(fā)器
}

通過調(diào)用dispatcher的enqueue方法進(jìn)行異步call分發(fā)

Dispatch的enqueue方法

synchronized void enqueue(AsyncCall call) { //分發(fā)器 分發(fā)任務(wù)  
    if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
        runningAsyncCalls.add(call);  //正在執(zhí)行的請(qǐng)求
        executorService().execute(call); //線程池跑任務(wù)
    } else {
        readyAsyncCalls.add(call);   //ready 中的任務(wù)什么時(shí)候執(zhí)行
    }
}
  • 如果正在執(zhí)行的請(qǐng)求小于64,相同host的請(qǐng)求不能超過5個(gè) 就放入運(yùn)行隊(duì)列runningAsyncCalls
  • 否則就放到準(zhǔn)備隊(duì)列readyAsyncCalls

如果在運(yùn)行隊(duì)列的call就會(huì)馬上放入executorService線程池進(jìn)行執(zhí)行

AsyncCall的execute方法:

 protected void execute() {
        boolean signalledCallback = false;
        try {
            //執(zhí)行請(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 {
                eventListener.callFailed(RealCall.this, e);
                responseCallback.onFailure(RealCall.this, e);
            }
        } finally {
            client.dispatcher().finished(this);  //這里的代碼肯定執(zhí)行
        }
    }
}

getResponseWithInterceptorChain:通過攔截器進(jìn)行網(wǎng)絡(luò)請(qǐng)求處理,重試被取消了回調(diào)失敗,否則正?;卣{(diào)onResponse。

注意finally里邊的內(nèi)容,最后會(huì)執(zhí)行dispatcher().finished(this)

dispatcher的finish方法

private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
    int runningCallsCount;
    Runnable idleCallback;
    synchronized (this) {
        //將任務(wù)都運(yùn)行隊(duì)列中移除
        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();
    }
}

這個(gè)里邊就是處理的隊(duì)列任務(wù)的切換,如果任務(wù)執(zhí)行完成之后,將運(yùn)行隊(duì)列的call移除,然后查看是否可以將等待隊(duì)列的任務(wù)放入運(yùn)行隊(duì)列。

2.3.分發(fā)器線程池

分發(fā)器就是來調(diào)配請(qǐng)求任務(wù)的,內(nèi)部會(huì)包含一個(gè)線程池。當(dāng)異步請(qǐng)求時(shí),會(huì)將請(qǐng)求任務(wù)交給線程池來執(zhí)行。那分發(fā)器中默認(rèn)的線程池是如何定義的呢

 public synchronized ExecutorService executorService() {
        if (executorService == null) {  //這個(gè)線程池的特點(diǎn)是高并發(fā) 最大吞吐量
            executorService = 
                new ThreadPoolExecutor(0, //核心線程數(shù)量
                                      Integer.MAX_VALUE,//最大線程數(shù)量
                                       60, 				//空閑線程閑置時(shí)間														TimeUnit.SECONDS,   //閑置時(shí)間單位
                    				new SynchronousQueue<Runnable>(),//線程等待隊(duì)列 
                    				Util.threadFactory("OkHttp Dispatcher",false)//線程工廠
                                      );
        }
        return executorService;
    }

首先核心線程為0,表示線程池不會(huì)一直為我們緩存線程,線程池中所有線程都是在60s內(nèi)沒有工作就會(huì)被回收。而最大線程 Integer.MAX_VALUE 與等待隊(duì)列 SynchronousQueue 的組合能夠得到最大的吞吐量。即當(dāng)需要線程池執(zhí)行任務(wù)時(shí),如果不存在空閑線程不需要等待,馬上新建線程執(zhí)行任務(wù)!等待隊(duì)列的不同指定了線程池的不同排隊(duì)機(jī)制。一般來說,等待隊(duì)列 BlockingQueue 有: ArrayBlockingQueue 、 LinkedBlockingQueue 與 SynchronousQueue 。

假設(shè)向線程池提交任務(wù)時(shí),核心線程都被占用的情況下:

ArrayBlockingQueue :基于數(shù)組的阻塞隊(duì)列,初始化需要指定固定大小。

當(dāng)使用此隊(duì)列時(shí),向線程池提交任務(wù),會(huì)首先加入到等待隊(duì)列中,當(dāng)?shù)却?duì)列滿了之后,再次提交任務(wù),嘗試加入

隊(duì)列就會(huì)失敗,這時(shí)就會(huì)檢查如果當(dāng)前線程池中的線程數(shù)未達(dá)到最大線程,則會(huì)新建線程執(zhí)行新提交的任務(wù)。所以

最終可能出現(xiàn)后提交的任務(wù)先執(zhí)行,而先提交的任務(wù)一直在等待。

LinkedBlockingQueue :基于鏈表實(shí)現(xiàn)的阻塞隊(duì)列,初始化可以指定大小,也可以不指定。

當(dāng)指定大小后,行為就和 ArrayBlockingQueu 一致。而如果未指定大小,則會(huì)使用默認(rèn)的 Integer.MAX_VALUE 作為隊(duì)列大小。這時(shí)候就會(huì)出現(xiàn)線程池的最大線程數(shù)參數(shù)無用,因?yàn)闊o論如何,向線程池提交任務(wù)加入等待隊(duì)列都會(huì)成功。最終意味著所有任務(wù)都是在核心線程執(zhí)行。如果核心線程一直被占,那就一直等待。

SynchronousQueue : 無容量的隊(duì)列。

使用此隊(duì)列意味著希望獲得最大并發(fā)量。因?yàn)闊o論如何,向線程池提交任務(wù),往隊(duì)列提交任務(wù)都會(huì)失敗。而失敗后

如果沒有空閑的非核心線程,就會(huì)檢查如果當(dāng)前線程池中的線程數(shù)未達(dá)到最大線程,則會(huì)新建線程執(zhí)行新提交的任

務(wù)。完全沒有任何等待,唯一制約它的就是最大線程數(shù)的個(gè)數(shù)。因此一般配合 Integer.MAX_VALUE 就實(shí)現(xiàn)了真正的無等待。

但是需要注意的時(shí),我們都知道,進(jìn)程的內(nèi)存是存在限制的,而每一個(gè)線程都需要分配一定的內(nèi)存。所以線程并不

能無限個(gè)數(shù)。那么當(dāng)設(shè)置最大線程數(shù)為 Integer.MAX_VALUE 時(shí),OkHttp同時(shí)還有最大請(qǐng)求任務(wù)執(zhí)行個(gè)數(shù): 64的限

堂制。這樣即解決了這個(gè)問題同時(shí)也能獲得最大吞吐。

3.OkHttp的攔截器

RealCall的getResponseWithInterceptorChain方法,是OkHttp最核心的部分

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) {//如果不是webSocket
        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);
}

這個(gè)方法就是進(jìn)行網(wǎng)絡(luò)請(qǐng)求的入口方法,進(jìn)過這個(gè)方法之后就拿到網(wǎng)絡(luò)請(qǐng)求的Response結(jié)果了。

這個(gè)方法里邊就是創(chuàng)建了一個(gè)List網(wǎng)絡(luò)攔截器的集合,將攔截器添加到集合里邊去。

retryAndFollowUpInterceptor:重試和重定向攔截器

  • client.interceptors():用戶自定義的攔截器
  • BridgeInterceptor:橋接攔截器
  • CacheInterceptor:緩存攔截器
  • ConnectInterceptor:連接攔截器
  • CallServerInterceptor:請(qǐng)求服務(wù)攔截器

創(chuàng)建鏈條RealInterceptorChain,調(diào)用鏈條的proceed方法

通過責(zé)任鏈設(shè)計(jì)模式,就會(huì)逐次訪問每個(gè)攔截器,攔截器是一個(gè)U型的數(shù)據(jù)傳遞過程。

PS:責(zé)任鏈設(shè)計(jì)模式,對(duì)象行為型模式,為請(qǐng)求創(chuàng)建了一個(gè)接收者對(duì)象的鏈,在處理請(qǐng)求的時(shí)候執(zhí)行過濾(各司職)。

責(zé)任鏈上的處理者負(fù)責(zé)處理請(qǐng)求,客戶只需要將請(qǐng)求發(fā)送到責(zé)任鏈即可,無須關(guān)心請(qǐng)求的處理細(xì)節(jié)和請(qǐng)求的傳遞所以職責(zé)鏈將請(qǐng)求的發(fā)送者和請(qǐng)求的處理者解耦了。

3.1.RetryAndFollowUpInterceptor 重試和重定向攔截器

RetryAndFollowUpInterceptor的intercept方法

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();
    /**
     *管理類,維護(hù)了 與服務(wù)器的連接、數(shù)據(jù)流與請(qǐng)求三者的關(guān)系。真正使用的攔截器為 Connect
     */
    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(request.url()), call, eventListener, callStackTrace);
    this.streamAllocation = streamAllocation;
    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
        if (canceled) {
            streamAllocation.release();
            throw new IOException("Canceled");
        }
        Response response;
        boolean releaseConnection = true;
        try {
            //請(qǐng)求出現(xiàn)了異常,那么releaseConnection依舊為true。
            response = realChain.proceed(request, streamAllocation, null, null);
            releaseConnection = false;
        } catch (RouteException e) {
            //路由異常,連接未成功,請(qǐng)求還沒發(fā)出去
            //The attempt to connect via a route failed. The request will not have been sent.
            if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
                throw e.getLastConnectException();
            }
            releaseConnection = false;
            continue;
        } catch (IOException e) {
            //請(qǐng)求發(fā)出去了,但是和服務(wù)器通信失敗了。(socket流正在讀寫數(shù)據(jù)的時(shí)候斷開連接)
            // HTTP2才會(huì)拋出ConnectionShutdownException。所以對(duì)于HTTP1 requestSendStarted一定是true
            //An attempt to communicate with a server failed. The request may have been sent.
            boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
            if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
            releaseConnection = false;
            continue;
        } finally {
            // We're throwing an unchecked exception. Release any resources.
            //不是前兩種的失敗,那直接關(guān)閉清理所有資源
            if (releaseConnection) {
                streamAllocation.streamFailed(null);
                streamAllocation.release();
            }
        }
        //如果進(jìn)過重試/重定向才成功的,則在本次響應(yīng)中記錄上次響應(yīng)的情況
        //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();
        }
        //處理3和4xx的一些狀態(tài)碼,如301 302重定向
        Request followUp = followUpRequest(response, streamAllocation.route());
        if (followUp == null) {
            if (!forWebSocket) {
                streamAllocation.release();
            }
            return response;
        }
        closeQuietly(response.body());
        //限制最大 followup 次數(shù)為20次
        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());
        }
        //todo 判斷是不是可以復(fù)用同一份連接
        if (!sameConnection(response, followUp.url())) {
            streamAllocation.release();
            streamAllocation = new StreamAllocation(client.connectionPool(),
                    createAddress(followUp.url()), call, eventListener, callStackTrace);
            this.streamAllocation = streamAllocation;
        } else if (streamAllocation.codec() != null) {
            throw new IllegalStateException("Closing the body of " + response
                    + " didn't close its backing stream. Bad interceptor?");
        }
        request = followUp;
        priorResponse = response;
    }
}

這個(gè)攔截器:第一個(gè)接觸到請(qǐng)求,最后接觸到響應(yīng);負(fù)責(zé)判斷是否需要重新發(fā)起整個(gè)請(qǐng)求

3.2.橋接攔截器BridgeInterceptor

BridgeInterceptor的intercept方法

public Response intercept(Chain chain) throws IOException {
    Request userRequest = chain.request();
    Request.Builder requestBuilder = userRequest.newBuilder();
    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");
    }
    // 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());
    HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    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")
                .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 ,連接應(yīng)用程序和服務(wù)器的橋梁,我們發(fā)出的請(qǐng)求將會(huì)經(jīng)過它的處理才能發(fā)給服務(wù)器,比如設(shè)

置請(qǐng)求內(nèi)容長度,編碼,gzip壓縮,cookie等,獲取響應(yīng)后保存Cookie等操作。

橋接攔截器的責(zé)任是:補(bǔ)全請(qǐng)求頭,并默認(rèn)使用gzip壓縮,同時(shí)將響應(yīng)體重新設(shè)置為gzip讀取。

3.3.緩存攔截器CacheInterceptor

CacheInterceptor的intercept方法,緩存的判斷條件比較復(fù)雜

public Response intercept(Chain chain) throws IOException {
    //通過url的md5數(shù)據(jù) 從文件緩存查找 (GET請(qǐng)求才有緩存)
    Response cacheCandidate = cache != null
            ? cache.get(chain.request())
            : null;
    long now = System.currentTimeMillis();
    //緩存策略:根據(jù)各種條件(請(qǐng)求頭)組成 請(qǐng)求與緩存
    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.
    }
    //沒有網(wǎng)絡(luò)請(qǐng)求也沒有緩存
    //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();
    }
    //沒有請(qǐng)求,肯定就要使用緩存
    //If we don't need the network, we're done.
    if (networkRequest == null) {
        return cacheResponse.newBuilder()
                .cacheResponse(stripBody(cacheResponse))
                .build();
    }
    //去發(fā)起請(qǐng)求
    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) {
        //服務(wù)器返回304無修改,那就使用緩存的響應(yīng)修改了時(shí)間等數(shù)據(jù)后作為本次請(qǐng)求的響應(yīng)
        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());
        }
    }
    //走到這里說明緩存不可用 那就使用網(wǎng)絡(luò)的響應(yīng)
    Response response = networkResponse.newBuilder()
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();
    //進(jìn)行緩存
    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 ,在發(fā)出請(qǐng)求前,判斷是否命中緩存。如果命中則可以不請(qǐng)求,直接使用緩存的響應(yīng)。 (只會(huì)存

在Get請(qǐng)求的緩存)

緩存是否存在,整個(gè)方法中的第一個(gè)判斷是緩存是不是存在,cacheResponse 是從緩存中找到的響應(yīng),如果為null,那就表示沒有找到對(duì)應(yīng)的緩存,創(chuàng)建的 CacheStrategy 實(shí)例對(duì)象只存在 networkRequest ,這代表了需要發(fā)起網(wǎng)絡(luò)請(qǐng)求。

https請(qǐng)求的緩存,繼續(xù)往下走意味著 cacheResponse 必定存在,但是它不一定能用,如果本次請(qǐng)求是HTTPS,但是緩存中沒有對(duì)應(yīng)的握手信息,那么緩存無效

響應(yīng)碼以及響應(yīng)頭,整個(gè)邏輯都在 isCacheable 中,緩存響應(yīng)中的響應(yīng)碼為 200, 203, 204, 300, 301, 404, 405, 410, 414, 501, 308 的情況下,只判斷服務(wù)器是不是給了Cache-Control: no-store (資源不能被緩存),所以如果服務(wù)器給到了這個(gè)響應(yīng)頭,那就和前面兩個(gè)判定一致(緩存不可用)。否則繼續(xù)進(jìn)一步判斷緩存是否可用

  • 響應(yīng)碼不為 200, 203, 204, 300, 301, 404, 405, 410, 414, 501, 308,302,307 緩存不可用
  • 當(dāng)響應(yīng)碼為302或者307時(shí),未包含某些響應(yīng)頭,則緩存不可用
  • 當(dāng)存在 Cache-Control: no-store 響應(yīng)頭則緩存不可用

用戶的請(qǐng)求配置,OkHttp需要先對(duì)用戶本次發(fā)起的 Request 進(jìn)行判定,如果用戶指定了 Cache-Control: no-cache (不使用緩存)的請(qǐng)求頭或者請(qǐng)求頭包含 If-Modified-Since 或 If-None-Match (請(qǐng)求驗(yàn)證),那么就不允許使用緩存

資源是否不變,如果緩存的響應(yīng)中包含 Cache-Control: immutable ,這意味著對(duì)應(yīng)請(qǐng)求的響應(yīng)內(nèi)容將一直不會(huì)改變。此時(shí)就可以直接使用緩存。否則繼續(xù)判斷緩存是否可用

3.4.連接攔截器ConnectInterceptor

ConnectInterceptor的intercept方法

public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    StreamAllocation streamAllocation = realChain.streamAllocation();
    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();
    return realChain.proceed(request, streamAllocation, httpCodec, connection);
}

雖然代碼量很少,實(shí)際上大部分功能都封裝到其它類去了,這里只是調(diào)用而已。

首先我們看到的 StreamAllocation 這個(gè)對(duì)象是在第一個(gè)攔截器:重定向攔截器創(chuàng)建的,但是真正使用的地方卻在

" 當(dāng)一個(gè)請(qǐng)求發(fā)出,需要建立連接,連接建立后需要使用流用來讀寫數(shù)據(jù) ";

而這個(gè)StreamAllocation就是協(xié)調(diào)請(qǐng)求、連接與數(shù)據(jù)流三者之間的關(guān)系,它負(fù)責(zé)為一次請(qǐng)求尋找連接,然后獲得流來實(shí)現(xiàn)網(wǎng)絡(luò)通信。

這里使用的 newStream 方法實(shí)際上就是去查找或者建立一個(gè)與請(qǐng)求主機(jī)有效的連接,返回的 HttpCodec 中包含了輸入輸出流,并且封裝了對(duì)HTTP請(qǐng)求報(bào)文的編碼與解碼,直接使用它就能夠與請(qǐng)求主機(jī)完成HTTP通信。

StreamAllocation 中簡單來說就是維護(hù)連接: RealConnection ——封裝了Socket與一個(gè)Socket連接池。可復(fù)用

的 RealConnection 需要:

3.5.請(qǐng)求服務(wù)器攔截器CallServerInterceptor

CallServerInterceptor的intercept方法

public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    HttpCodec httpCodec = realChain.httpStream();
    StreamAllocation streamAllocation = realChain.streamAllocation();
    RealConnection connection = (RealConnection) realChain.connection();
    Request request = realChain.request();
    long sentRequestMillis = System.currentTimeMillis();
    realChain.eventListener().requestHeadersStart(realChain.call());
    httpCodec.writeRequestHeaders(request);
    realChain.eventListener().requestHeadersEnd(realChain.call(), request);
    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.
         //這個(gè)請(qǐng)求頭代表了在發(fā)送請(qǐng)求體之前需要和服務(wù)器確定是否愿意接受客戶端發(fā)送的請(qǐng)求體
        //但是如果服務(wù)器不同意接受請(qǐng)求體,那么我們就需要標(biāo)記該連接不能再被復(fù)用,調(diào)用 noNewStreams() 關(guān)閉相關(guān)的Socket。
        if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
            httpCodec.flushRequest();
            realChain.eventListener().responseHeadersStart(realChain.call());
            responseBuilder = httpCodec.readResponseHeaders(true);
        }
        if (responseBuilder == null) {
            // Write the request body if the "Expect: 100-continue" expectation was met.
            realChain.eventListener().requestBodyStart(realChain.call());
            long contentLength = request.body().contentLength();
            CountingSink requestBodyOut =
                    new CountingSink(httpCodec.createRequestBody(request, contentLength));
            BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
            request.body().writeTo(bufferedRequestBody);
            bufferedRequestBody.close();
            realChain.eventListener()
                    .requestBodyEnd(realChain.call(), requestBodyOut.successfulCount);
        } else if (!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.
            streamAllocation.noNewStreams();
        }
    }
    httpCodec.finishRequest();
    if (responseBuilder == null) {
        realChain.eventListener().responseHeadersStart(realChain.call());
        responseBuilder = httpCodec.readResponseHeaders(false);
    }
    Response response = responseBuilder
            .request(request)
            .handshake(streamAllocation.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
        responseBuilder = httpCodec.readResponseHeaders(false);
        response = responseBuilder
                .request(request)
                .handshake(streamAllocation.connection().handshake())
                .sentRequestAtMillis(sentRequestMillis)
                .receivedResponseAtMillis(System.currentTimeMillis())
                .build();
        code = response.code();
    }
    realChain.eventListener()
            .responseHeadersEnd(realChain.call(), 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(httpCodec.openResponseBody(response))
                .build();
    }
    if ("close".equalsIgnoreCase(response.request().header("Connection"))
            || "close".equalsIgnoreCase(response.header("Connection"))) {
        streamAllocation.noNewStreams();
    }
    if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
        throw new ProtocolException(
                "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
    }
    return response;
}

調(diào)用 httpCodec.writeRequestHeaders(request); 將請(qǐng)求頭寫入到緩存中(直到調(diào)用 flushRequest() 才真正發(fā)

送給服務(wù)器)。

CallServerInterceptor ,利用 HttpCodec 發(fā)出請(qǐng)求到服務(wù)器并且解析生成 Response,在這個(gè)攔截器中就是完成HTTP協(xié)議報(bào)文的封裝與解析。

4.OkHttp總結(jié)

整個(gè)OkHttp功能的實(shí)現(xiàn)就在這五個(gè)默認(rèn)的攔截器中,所以先理解攔截器模式的工作機(jī)制是先決條件。

這五個(gè)攔截器分別為:

重試攔截器

重試攔截器在交出(交給下一個(gè)攔截器)之前,負(fù)責(zé)判斷用戶是否取消了請(qǐng)求;在獲得了結(jié)果之后,會(huì)根據(jù)響應(yīng)碼判斷是否需要重定向,如果滿足條件那么就會(huì)重啟執(zhí)行所有攔截器

橋接攔截器

橋接攔截器在交出之前,負(fù)責(zé)將HTTP協(xié)議必備的請(qǐng)求頭加入其中(如:Host)并添加一些默認(rèn)的行為(如:GZIP壓縮);在獲得了結(jié)果后,調(diào)用保存cookie接口并解析GZIP數(shù)據(jù)

緩存攔截器

緩存攔截器顧名思義,交出之前讀取并判斷是否使用緩存;獲得結(jié)果后判斷是否緩存

連接攔截器

連接攔截器在交出之前,負(fù)責(zé)找到或者新建一個(gè)連接,并獲得對(duì)應(yīng)的socket流;在獲得結(jié)果后不進(jìn)行額外的處理。

請(qǐng)求服務(wù)攔截器

請(qǐng)求服務(wù)器攔截器進(jìn)行真正的與服務(wù)器的通信,向服務(wù)器發(fā)送數(shù)據(jù),解析讀取的響應(yīng)數(shù)據(jù)。

每一個(gè)攔截器負(fù)責(zé)的工作不一樣,就好像工廠流水線,最終經(jīng)過這五道工序,就完成了最終的產(chǎn)品。

到此這篇關(guān)于Android OKHttp框架的分發(fā)器與攔截器源碼刨析的文章就介紹到這了,更多相關(guān)Android分發(fā)器與攔截器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論