Okhttp3源碼解析(5)-攔截器RetryAndFollowUpInterceptor

来源:https://www.cnblogs.com/qinzishuai/archive/2019/08/29/11427631.html
-Advertisement-
Play Games

### 前言 回顧: [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源碼解析(1)-OkHttpClient分析](https://www.jianshu.com/p/bf1d01b79ce7) [Okhttp3源碼解析( ...


### 前言 回顧: [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源碼解析(1)-OkHttpClient分析](https://www.jianshu.com/p/bf1d01b79ce7) [Okhttp3源碼解析(2)-Request分析](https://www.jianshu.com/p/5a85345c8ea7) [Okhttp3源碼解析(3)-Call分析(整體流程)](https://www.jianshu.com/p/4ed79472797a) [Okhttp3源碼解析(4)-攔截器與設計模式](https://www.jianshu.com/p/b8817597f269) 上節講了攔截器與設計模式,今天講`RetryAndFollowUpInterceptor`,如果我們沒有去自定義攔截器, 那`RetryAndFollowUpInterceptor`是第一個攔截器。 ### 初始化 首先先看`RetryAndFollowUpInterceptor`被添加的位置: ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084744888-554996670.png) 初始化位置: call實例化方法中: ``` private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) { this.client = client; this.originalRequest = originalRequest; this.forWebSocket = forWebSocket; this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket); } ``` 找到了初始化的位置, 下麵去`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(); 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 { 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(), streamAllocation, false, request)) { throw e.getFirstConnectException(); } 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, streamAllocation, 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.newBuilder() .priorResponse(priorResponse.newBuilder() .body(null) .build()) .build(); } Request followUp; try { followUp = followUpRequest(response, streamAllocation.route()); } catch (IOException e) { streamAllocation.release(); throw e; } if (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); 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; } } ``` 我先貼出一個`while迴圈`的流程圖: ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084745296-805720763.png) 根據流程圖和源碼可以分析`RetryAndFollowUpInterceptor`主要做了以下內容,**後兩點都是發生在`while迴圈`中**: - **初始化StreamAllocation 對象** - **網路請求-chain.proceed() ,對在請求時發生的異常進行捕獲以及對應的重連機制** - **followUpRequest 對響應碼進行處理** 下麵可以逐塊代碼分析: ###### 1.初始化StreamAllocation 對象 `StreamAllocation`類是**協調三個實體之間的關係** 三個實體是:`Connections`,`Streams`,`Calls` 我們請求網路時需要傳遞它 ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084745679-501952792.png) `StreamAllocation`在這大家簡單瞭解一下就可以了. ###### 2.網路請求時異常捕獲-以及重連機制 網路請求如下: ``` response = realChain.proceed(request, streamAllocation, null, null); ``` 如果請求發現異常,我們通過try/catch捕獲 ``` catch (RouteException e) { // The attempt to connect via a route failed. The request will not have been sent. if (!recover(e.getLastConnectException(), streamAllocation, false, request)) { throw e.getFirstConnectException(); } 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, streamAllocation, requestSendStarted, request)) throw e; releaseConnection = false; continue; } ``` -`RouteException` 路由異常 - `IOException` IO異常 捕獲後都做了`recover()`重連判斷,具體代碼如下,就不細說了: ``` private boolean recover(IOException e, StreamAllocation streamAllocation, boolean requestSendStarted, Request userRequest) { streamAllocation.streamFailed(e); // The application layer has forbidden retries. if (!client.retryOnConnectionFailure()) return false; // We can't send the request body again. if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false; // This exception is fatal. if (!isRecoverable(e, requestSendStarted)) return false; // No more routes to attempt. if (!streamAllocation.hasMoreRoutes()) return false; // For failure recovery, use the same route selector with a new connection. return true; } ``` 這裡需要註意的是如果可以重連,執行 continue; `continue`含義: 繼續迴圈,(不執行 迴圈體內`continue` 後面的語句,直接進行下一迴圈) ###### 3.` followUpRequest` 對響應碼進行處理 先看看具體`followUpRequest `方法: ``` private Request followUpRequest(Response userResponse, Route route) throws IOException { if (userResponse == null) throw new IllegalStateException(); int responseCode = userResponse.code(); final String method = userResponse.request().method(); switch (responseCode) { case HTTP_PROXY_AUTH: Proxy selectedProxy = route != null ? route.proxy() : client.proxy(); if (selectedProxy.type() != Proxy.Type.HTTP) { throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy"); } return client.proxyAuthenticator().authenticate(route, userResponse); case HTTP_UNAUTHORIZED: return client.authenticator().authenticate(route, userResponse); case HTTP_PERM_REDIRECT: case HTTP_TEMP_REDIRECT: // "If the 307 or 308 status code is received in response to a request other than GET // or HEAD, the user agent MUST NOT automatically redirect the request" if (!method.equals("GET") && !method.equals("HEAD")) { return null; } // fall-through case HTTP_MULT_CHOICE: case HTTP_MOVED_PERM: case HTTP_MOVED_TEMP: case HTTP_SEE_OTHER: // Does the client allow redirects? if (!client.followRedirects()) return null; String location = userResponse.header("Location"); if (location == null) return null; HttpUrl url = userResponse.request().url().resolve(location); // Don't follow redirects to unsupported protocols. if (url == null) return null; // If configured, don't follow redirects between SSL and non-SSL. boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme()); if (!sameScheme && !client.followSslRedirects()) return null; // Most redirects don't include a request body. Request.Builder requestBuilder = userResponse.request().newBuilder(); if (HttpMethod.permitsRequestBody(method)) { final boolean maintainBody = HttpMethod.redirectsWithBody(method); if (HttpMethod.redirectsToGet(method)) { requestBuilder.method("GET", null); } else { RequestBody requestBody = maintainBody ? userResponse.request().body() : null; requestBuilder.method(method, requestBody); } if (!maintainBody) { requestBuilder.removeHeader("Transfer-Encoding"); requestBuilder.removeHeader("Content-Length"); requestBuilder.removeHeader("Content-Type"); } } // When redirecting across hosts, drop all authentication headers. This // is potentially annoying to the application layer since they have no // way to retain them. if (!sameConnection(userResponse, url)) { requestBuilder.removeHeader("Authorization"); } return requestBuilder.url(url).build(); case HTTP_CLIENT_TIMEOUT: // 408's are rare in practice, but some servers like HAProxy use this response code. The // spec says that we may repeat the request without modifications. Modern browsers also // repeat the request (even non-idempotent ones.) if (!client.retryOnConnectionFailure()) { // The application layer has directed us not to retry the request. return null; } if (userResponse.request().body() instanceof UnrepeatableRequestBody) { return null; } if (userResponse.priorResponse() != null && userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) { // We attempted to retry and got another timeout. Give up. return null; } if (retryAfter(userResponse, 0) > 0) { return null; } return userResponse.request(); case HTTP_UNAVAILABLE: if (userResponse.priorResponse() != null && userResponse.priorResponse().code() == HTTP_UNAVAILABLE) { // We attempted to retry and got another timeout. Give up. return null; } if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) { // specifically received an instruction to retry without delay return userResponse.request(); } return null; default: return null; } } ``` 不難看出, 是根據響應碼進行判斷的。 - HTTP_PROXY_AUTH 407 代理身份驗證 - HTTP_UNAUTHORIZED 401 未授權 - HTTP_PERM_REDIRECT 308 重定向 - HTTP_TEMP_REDIRECT 307 重定向 - HTTP_MULT_CHOICE 300 Multiple Choices - HTTP_MOVED_PERM 301 Moved Permanently - HTTP_MOVED_TEMP 302 Temporary Redirect - HTTP_SEE_OTHER 303 See Other - HTTP_CLIENT_TIMEOUT 408 Request Time-Out - HTTP_UNAVAILABLE 503 Service Unavailable 對於這些響應碼都做了處理: 1.返回null ``` if (followUp == null) { if (!forWebSocket) { streamAllocation.release(); } return response; } ``` 2.其他異常情況直接拋異常了 強調: `MAX_FOLLOW_UPS`欄位, 表示最大的重定向次數 ``` /** * How many redirects and auth challenges should we attempt? Chrome follows 21 redirects; Firefox, * curl, and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5. */ private static final int MAX_FOLLOW_UPS = 20; ``` ``` if (++followUpCount > MAX_FOLLOW_UPS) { streamAllocation.release(); throw new ProtocolException("Too many follow-up requests: " + followUpCount); } ``` 這節就說到這,希望對大家有所幫助..... ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084746645-654895211.png) 大家可以關註我的微信公眾號:「秦子帥」一個有質量、有態度的公眾號! ![公眾號](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190829084746832-730035128.jpg)
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、系統基礎 1、三大部件: CPU:運算器、控制器、存儲器 記憶體:CPU的數據只能從記憶體中讀取,且記憶體數據是易失性的(頁面) IO: 控制匯流排、數據匯流排 2、OS的管理 GUI:圖形用戶界面 GNOME KDE XFCE CLI:命令行管理界面 shell 常見的shell程式: sh bash ...
  • 安裝WebPlatformInstaller_x64_en-US,導致了IIS應用被訪問時,應用程式池自動關閉的問題。 ...
  • 這樣的sql咋樣? ...
  • 8月28日,騰訊雲資料庫在京正式啟動戰略升級,宣佈未來將聚焦雲原生、自治、超融合三大戰略方向,以用戶為中心,聯接未來。併在現場面向全球用戶同步發佈五大戰略級新品,包括資料庫智能管家DBbrain、雲資料庫TBase、資料庫備份服務DBS、雲資料庫Redis混合存儲版,以及自研雲原生資料庫CynosD ...
  • ​ 數據架構設計領域正在發生一場變革,其影響的不僅是實時處理業務,這場變革可能將基於流的處理視為整個架構設計的核心,而不是將流處理只是作為某一個實時計算的項目使用。本文將對比傳統數據架構與流處理架構的區別,並將介紹如何將流處理架構應用於微服務及整體系統中。 傳統數據架構 ​ 傳統數據架構是一種中心化 ...
  • ...
  • 1、先卸載當前系統中已安裝的mariadb 2、安裝mysql依賴包 3、下載mysql 4、解壓mysql壓縮包,創建mysql目錄 5、創建mysql虛擬用戶和組 6、配置/etc/my.cnf 7、配置環境變數 8、初始化資料庫 初始化完成後,會自動為root帳戶生成一個初始密碼,要記錄下來 ...
  • 隨著在Andriod設備上使用UHF讀寫器變得越來越廣泛,友我科技獨立研發了UHF讀寫器的android開發包,使用此開發包,工程師只需在工程中導入jar包,使用java語言就可以輕鬆的開發出Android下的UHF讀寫器應用APP。支持jar包的UHF讀寫器有YW-602H。 在jar介面包里,包 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...