文章目錄
- OkHttp
- Demo代碼
- 流程圖
- 攔截器 Interceptor
- RetryAndFollowUpInterceptor
- BridgeInterceptor
- CacheInterceptor
- ConnectInterceptor
- networkInterceptors
- CallServerInterceptor
- `CacheInterceptor`快取詳解
- Cache.java
- CacheStrategy.java 快取策略
- okhttp3.Dispatcher 異步請求調度
- Http Header配置知識
- 查看http請求頭的方式
- 常見配置項
- 快取 Cache-Control
- 協商快取`Last-Modify/If-Modify-Since`,`If-None-Match/ETag`
- Range和Content-Range
- User-Agent
- SSL加密方式配置
- RealCall類
- Http 協議
- http2.0
- Java方法
- 未研究
OkHttp
- 官網檔案: https://square.github.io/okhttp/
- 設計模式: 建造者模式、責任鏈模式
- 物件池,連接池
Demo代碼
addInterceptor:應用層攔截器,在網路請求前攔截,addNetworkInterceptor:網路層攔截器,在發起網路請求后,進行攔截,callTimeout:本次請求的總體超時時間,包括connect、write、read等階段時間,connectTimeout:連接階段超時時間,默認10秒,配置tcp層socket引數,java.net.Socket#connect(java.net.SocketAddress, int),參考Okhttp原始碼RealConnection#connectSocket,readTimeout:socketread函式超時時間,默認10秒,配置tcp層socket引數,java.net.Socket#setSoTimeout,參考Okhttp原始碼RealConnection#connectSocket,writeTimeout:連接階段超時時間,默認10秒,
// 定義一個攔截器
Interceptor interceptor = chain -> {
Request request = chain.request();
long t1 = System.nanoTime();
Log.i(TAG, String.format("Send request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.i(TAG, String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
};
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor) // 應用層攔截器,在網路連接前生效
.addNetworkInterceptor(interceptor) // 網路請求前的攔截器,在網路連接后生效
.cache(new Cache(new File("/data/data/com.test.http/cache", "http_cache"), 50 * 1024 * 1024)) // 50 MB
.callTimeout(5, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.eventListener(new EventListener(){})
.build();
CacheControl cacheControl = new CacheControl.Builder()
.noCache() // 即使有快取,每次也都發起網路請求,收到304相應后,使用快取,否則更新快取,
.maxAge(60, TimeUnit.SECONDS)
// .onlyIfCached() //
.build();
Request request = new Request.Builder()
.url("https://github.com/square/okhttp")
.cacheControl()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Log.i(TAG, "onFailure " + call.request());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse " + call.request() + ", Response Content" + response);
}
});
流程圖

攔截器 Interceptor

- 官網檔案: https://square.github.io/okhttp/interceptors/
- 快取攔截器: https://juejin.cn/post/6845166891476992008
- 無論是異步請求還是同步請求都會通過
RealCall#getResponseWithInterceptorChain這個函式來遍歷攔截器,發起網路請求,攔截器是按照添加順序進行遍歷的, - 攔截器的遍歷執行順序:
client.interceptors()、RetryAndFollowUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor、client.networkInterceptors()、CallServerInterceptor, okhttp3.Interceptor.Chain介面的唯一實作類是RealInterceptorChain,通過該類的RealInterceptorChain#proceed(okhttp3.Request)實作遍歷攔截器的操作,
// okhttp3.RealCall#getResponseWithInterceptorChain
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors()); // 自定義應用攔截器
interceptors.add(new RetryAndFollowUpInterceptor(client)); // 重試、重定向攔截器
interceptors.add(new BridgeInterceptor(client.cookieJar())); // 橋接攔截器,主要是修改header引數、gzip壓縮
interceptors.add(new CacheInterceptor(client.internalCache())); // 快取
interceptors.add(new ConnectInterceptor(client)); // 待研究
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors()); // 待研究
}
interceptors.add(new CallServerInterceptor(forWebSocket)); // 待研究
// okhttp3.Interceptor#intercept方法chain引數的實際型別
Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,
originalRequest, this, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
boolean calledNoMoreExchanges = false;
try {
Response response = chain.proceed(originalRequest);
if (transmitter.isCanceled()) {
closeQuietly(response);
throw new IOException("Canceled");
}
return response;
} catch (IOException e) {
calledNoMoreExchanges = true;
throw transmitter.noMoreExchanges(e);
} finally {
if (!calledNoMoreExchanges) {
transmitter.noMoreExchanges(null);
}
}
}
- 通過
index的累加,實作對interceptors的遍歷,設計模式的責任鏈模式,
// okhttp3.internal.http.RealInterceptorChain#proceed(okhttp3.Request, okhttp3.internal.connection.Transmitter, okhttp3.internal.connection.Exchange)
public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange)
throws IOException {
// 省略例外檢查代碼.....
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, transmitter, exchange,
index + 1, request, call, connectTimeout, readTimeout, writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
// 省略對Response的例外檢查代碼.....
return response;
}
RetryAndFollowUpInterceptor
- 默認情況下是會進行重試,默認的配置引數是
OkHttpClient.Builder#retryOnConnectionFailure(boolean) - 重試、重定向攔截器
- 重定向函式
RetryAndFollowUpInterceptor#followUpRequest,做多重定向20次
BridgeInterceptor
- 相對還比較簡單,主要是想Http Header里面添加了一些欄位配置,
- 最主要的是自動添加了
gzip壓縮配置,同時對收到的資料解壓縮 - 配置了
Connection:Keep-Alive代表需要長連接\
// okhttp3.internal.http.BridgeInterceptor#intercept
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");
}
CacheInterceptor
- 參考
CacheInterceptor快取詳解章節,
ConnectInterceptor
- 參考
連接攔截器篇:https://blog.csdn.net/followYouself/article/details/121086869
networkInterceptors
- 自定義的網路決議攔截器,
- 在和服務器建立連接之后,在真正的發起網路請求之前進行攔截,
CallServerInterceptor
- 實際使用
Okio向服務器進行互動,進行request請求,接收response, Http2相關的請求類Http2Stream.java,Http2Reader,Http2Writer,
CacheInterceptor快取詳解
- 默認情況下,不開啟任何快取,開啟快取需要通過
OkHttpClient.Builder#cache(@Nullable Cache cache)方法進行配置,指定快取File檔案路徑, - okhttp只會對get請求進行快取,
- url作為快取的key資訊,
CacheControl一些關鍵配置no-cache、no-store、max-age、only-if-cached、max-stale,參考下文Http header章節- 如果服務端不支持快取配置,也可以source端實作快取,可以通過
addNetworkInterceptor,在Response中增加cache-control,配置max-age(優先級高),Last-Modify(優先級低)等引數,參考原始碼CacheStrategy.Factory#computeFreshnessLifetime, - 官網: https://square.github.io/okhttp/caching/
- 參考資料:https://juejin.cn/post/6850418120729985038,這個wiki有個問題,混淆了
noCache和noStore
Cache.java
get、put、remove、update分別對應快取的讀、寫、洗掉、更新操作,DiskLruCache封裝了快取讀寫的能力,利用了Okio的讀寫能力,參考資料:https://blog.csdn.net/zwlove5280/article/details/79916662- 快取的鍵值是request的url,參考
okhttp3.Cache#key方法, - Response的
Header資訊存盤在.0檔案,body資訊存盤在.1檔案,所有操作的日志記錄在journal檔案, - 如何讀寫的細節以及
DiskLruCache細節沒有研究,
CacheStrategy.java 快取策略
- 根據request請求和快取中的Response決定后續的網路請求步驟,關鍵方法是
CacheStrategy.Factory#get()、CacheStrategy.Factory#getCandidate() - 這個類有兩個成員變數
networkRequest不為空,表示需要發起網路請求,null,則表示不需要網路請求,cacheResponse不為null,該快取需要驗證或者直接作為結果,為null,表示不使用快取, - 需要特別注意的是,如果
networkRequest不為空,同時request也配置了only-if-cached,那么會報504錯誤,Unsatisfiable Request (only-if-cached), CacheStrategy#isCacheable,首先判斷Response的狀態碼是否支持快取,然后在檢查Response和Request的header,如果配置了no-store,那么不支持快取,- 快取策略 之
CacheStrategy.Factory#getCandidate函式,代碼中的注釋 1,2,3分別與下面對應
- 如果在cache中沒有找到
cacheResponse,那么需要網路請求, - 如果是https請求,但是
cacheResponse中沒有handshake,那么需要網路請求, isCacheable判斷cacheResponse中的狀態碼是否支持快取,同時判斷request請求是否配置了noStore,如果配置了noStore,那么禁止使用快取,- 如果請求配置了
noCache或者配置了If-Modified-Since或者配置了If-None-Match,那么直接發起網路請求,根據CacheInterceptor.java代碼,網路請求完成后,如果cacheResponse不為空,并且收到304狀態碼,那么使用cacheResponse作為請求結果, - 根據
request的maxage、min-fresh、maxStale,以及根據cacheResponse的sentRequestAtMillis、receivedResponseAtMillis、servedDate、must-revalidate等配置,計算cacheResponse是否過期,是否滿足本次的request的要求,如果滿足,那么直接使用快取作為網路請求的結果,不發起實際的網路請求,具體的計算細節沒研究… - 此處根據時間計算,判斷是否使用快取,
ageMillis:cacheResponse從生成到現在的耗時;minFreshMillis:最小新鮮度,距離最終過期的最短時間,request中配置;freshMillis:cacheResponse和request配置的max-age中的較小值;maxStaleMillis在超過max-age后,仍然可以接受的時間,request中配置, - 在上述條件均沒有滿足,快取也過期的情況下,依次 判斷
cacheResponse是否攜帶了ETag、Last-Modified、Date等欄位,轉換為If-None-Match和If-Modified-Since欄位,添加到request header中, - 如果
networkRequest不為空,同時request也配置了only-if-cached,根據CacheInterceptor.java代碼,會上報504錯誤,Unsatisfiable Request (only-if-cached),

// okhttp3.internal.cache.CacheStrategy.Factory
/**
* Returns a strategy to satisfy {@code request} using the a cached response {@code response}.
*/
public CacheStrategy get() {
CacheStrategy candidate = getCandidate(); // 根據request請求和快取中的Response決定后續的網路請求步驟
// 禁止同時有networkRequest 和 onlyIfCached配置,
if (candidate.networkRequest != null && request.cacheControl().onlyIfCached()) { // 注釋8
// We're forbidden from using the network and the cache is insufficient.
return new CacheStrategy(null, null); // 此處為空,會報`504`錯誤,
}
return candidate;
}
/** Returns a strategy to use assuming the request can use the network. */
private CacheStrategy getCandidate() {
// No cached response.
if (cacheResponse == null) { // 注釋1
return new CacheStrategy(request, null);
}
// Drop the cached response if it's missing a required handshake.
if (request.isHttps() && cacheResponse.handshake() == null) { // 注釋2
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)) { // 注釋3
return new CacheStrategy(request, null);
}
CacheControl requestCaching = request.cacheControl(); // 獲取請求中的cacheControl配置
if (requestCaching.noCache() || hasConditions(request)) { // 注釋4
return new CacheStrategy(request, null);
}
CacheControl responseCaching = cacheResponse.cacheControl(); // 注釋5
long ageMillis = cacheResponseAge(); // 計算快取從生成開始,已經度過了多長時間
long freshMillis = computeFreshnessLifetime(); // 回傳Response配置的max-age,最大可存活的生命時間
if (requestCaching.maxAgeSeconds() != -1) {
// cacheResponse中配置的max-age 和 request中配置的max-age中,取最小的一個值,
// 此處就最終計算出來允許Response有效時間
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());
}
// 如果快取沒有過期,滿足當前request的要求,那么直接使用快取作為結果,
if (!responseCaching.noCache() && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) { // 注釋6
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 (etag != null) { // 注釋7
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
Request conditionalRequest = request.newBuilder()
.headers(conditionalRequestHeaders.build())
.build();
return new CacheStrategy(conditionalRequest, cacheResponse);
}
okhttp3.Dispatcher 異步請求調度
maxRequests最大并發請求數量,默認64,maxRequestsPerHost每個主機host支持的最大并發請求數量,默認5,可配置,- 包含一個執行緒池
executorService,用于異步的網路請求調度,默認的配置為核心執行緒為0,最大執行緒數不限制,存活時間60秒,
// okhttp3.Dispatcher#executorService
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false));
Http Header配置知識
查看http請求頭的方式
- 瀏覽器內,F12
- F5 重繪網頁
- NetWork選項卡,Doc選項卡,在Name中選擇一次請求
- 選擇Headers選項卡,(和Header選項卡并列的有Preview、Response、Cookies)
常見配置項
Accept-Encoding:gzip代表壓縮編碼資料Connection:Keep-Alive代表需要長連接
快取 Cache-Control
no-cache:資源是可以被客戶端快取的,代理服務器不快取,但是每次請求都需要先到服務端驗證資源是否有效,相關配置參考Last-Modify / If-Modify-Sinceno-store:禁止任何形式的快取,客戶端和服務端均可進行配置生效,max-age:資源可以被快取的時間,單位秒,max-age會覆寫掉expires,超期后,訪問服務器校驗有效性,s-maxage:設定代理服務器快取的最大的有效時間,單位秒,s-maxage會覆寫掉max-age,public:表示當前的請求是一種通用的業務資料,客戶端、代理服務器、中間節點服務器都可以快取這些資料,private:默認值,表示當前的操作是和具體用戶強相關的特殊行為,不應該在代理類服務器、中間節點服務器等進行快取,因為快取并沒有很大的意義,only-if-cached:不進行網路請求,完全只使用快取.如果快取不命中,回傳504錯誤,并且此處的優先級要高于no-cache,肯定不會發起網路請求了,must-revalidate: 資源一旦過期,則必須向服務器發起請求確認資源有效性,如果無法訪問服務器,則上報 504 Gateway Timeout,優先級高于max-stale,設定之后max-stale變為無效,max-stale:客戶端要求快取代理該時間內(默認不限時間)的資源無論快取有沒有過期都回傳給客戶端,這個引數表示業務可以接受的回應的過期時間,no-transform:快取代理不可更改媒體型別,這樣可以防止壓縮圖片、壓縮資源的操作min-fresh:距離快取Response過期(max-age、max-stale之和)剩余的最小時間,保證取到快取不會在短時間(min-fresh)內超期無效,比如max-age=100,max-stale=500,min-fresh=200,那么Response的max-age+max-stale和是600,由于配置了min-fresh,那么要求在使用快取是,必須保證距離600這個最終過期時間點,保留200的新鮮度,600 - 200 = 400,那么也就是快取的Response從快取開始到現在nowTime最多度過了400的時間長度,才可以使用,- 參考資料 https://segmentfault.com/a/1190000022336086
協商快取Last-Modify/If-Modify-Since,If-None-Match/ETag
etag的校驗優先級高于Last-Modify,Last-Modify:在服務器的Response中攜帶,表示業務資料上次被修改的時間If-Modify-Since:當快取過期時,在客戶端request請求時攜帶,服務器上檢查request的請求時間,并校驗服務器資源是否被修改,如果被修改,那么回傳最新資料,并回傳HTTP 200 OK,如果資源沒有修改,那么僅僅回傳狀態碼HTTP 304etag:服務器Response攜帶的資源tag,資源的任何修改都會導致tag的改變,如果tag不變,是可以表示資源資料沒有變化的,If-None-Match:當快取過期時,客戶端request的請求中攜帶,攜帶的是快取中Response的tag值,同樣是根據tag判斷資源資料是否被修改,相應客戶端請求,
Range和Content-Range
- 范圍引數,可以制定要從服務器獲取檔案的范圍,
- 設計目的:用于斷點續傳,比如下載大檔案時,網路突然中斷,恢復網路時,可以繼續下載內容,
User-Agent
- 代表用戶行為的程式軟體,比如,網頁瀏覽器就是一個“幫助用戶獲取、渲染網頁內容并與之互動”的用戶代理;電子郵件閱讀器也可以稱作郵件代理,
- 舉例
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36
SSL加密方式配置
- 配置函式
OkHttpClient#sslSocketFactory, 默認配置函式OkHttpClient#newSslSocketFactory, - 分為Android平臺和java平臺,Android平臺的配置函式是
AndroidPlatform#getSSLContext,原始碼如下
@Override
public SSLContext getSSLContext() {
boolean tryTls12;
try {
tryTls12 = (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22);
} catch (NoClassDefFoundError e) {
// Not a real Android runtime; probably RoboVM or MoE
// Try to load TLS 1.2 explicitly.
tryTls12 = true;
}
if (tryTls12) {
try {
return SSLContext.getInstance("TLSv1.2");
} catch (NoSuchAlgorithmException e) {
// fallback to TLS
}
}
try {
return SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No TLS provider", e);
}
}
- CLEARTEXT是用于不安全配置的http://網址,
RealCall類

Http 協議
- http1.0、http1.1、http2.0、http3.0
http2.0
- http2.0 和http1.0 的區別:http2.0支持多路復用,支持多個請求并發傳輸,http1.0是順序執行的,發送一個請求之后,等到回應之后,才能發起下一個請求,
- http2.0中重要的概念是
幀(frame)和流(stream),每一個流都是有一個獨一無二的編號, - HTTP2.0 訊息頭的壓縮演算法采用 HPACK,
- http2.0:https://segmentfault.com/a/1190000016975064
- http2.0:https://juejin.cn/post/6844903935648497678
Java方法
- java.lang.Thread#holdsLock 判斷當前執行緒是否持有某個鎖
未研究
- 各個版本的
http協議區別,協議的細節, Okio開源庫作為基礎讀寫庫,沒有閱讀原始碼,Okio的實作原理不了解,segment機制,DiskLruCache.java檔案快取方案,沒有閱讀原始碼Http2Connection.javahttp2協議的連接,資料收發,stream使用相關資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/345785.html
標籤:其他
