系統(tǒng)學(xué)習(xí)詳見OKhttp源碼解析詳解系列
1 http協(xié)議中的重定向
- client:向server發(fā)送一個請求,要求獲取一個資源
- server:接收到這個請求后,發(fā)現(xiàn)請求的這個資源實際存放在另一個位置于是server在返回的response header的Location字段中寫入那個請求資源的正確的URL,并設(shè)置reponse的狀態(tài)碼為30x
- client:接收到這個response后,發(fā)現(xiàn)狀態(tài)碼為重定向的狀態(tài)嗎,就會去解析到新的URL,根據(jù)新的URL重新發(fā)起請求
2 狀態(tài)碼
- 重定向最常用為301,也有303,
- 臨時重定向用302,307

57e963c7b3caae3dbf19e265114212d2.png
3 與請求轉(zhuǎn)發(fā)的對比
- 請求轉(zhuǎn)發(fā)
- 服務(wù)器在處理request的過程中將request先后委托多個servlet或jsp接替進(jìn)行處理的過程,request和reponse始終在期間傳遞
- 區(qū)別
- 重定向時,客戶端發(fā)起兩次請求,而請求轉(zhuǎn)發(fā)時,客戶端只發(fā)起一次請求
- 重定向后,瀏覽器地址欄url變成第二個url,而請求轉(zhuǎn)發(fā)沒有變(請求轉(zhuǎn)發(fā)對于客戶端是透明的)
- 流程
重定向:
用戶請求-----》服務(wù)器入口-------》組件------>服務(wù)器出口-------》用戶----(重定向)---》新的請求
請求轉(zhuǎn)發(fā)
用戶請求-----》服務(wù)器入口-------》組件1---(轉(zhuǎn)發(fā))----》組件2------->服務(wù)器出口-------》用戶
4 RetryAndFollowUpInterceptor攔截器
RetryAndFollowUpInterceptor負(fù)責(zé)失敗重試以及重定向。
RetryAndFollowUpInterceptor的作用就是處理了一些連接異常以及重定向。
4.0 重定向流程
- 第一次請求返回response,followUpRequest根據(jù)響應(yīng)碼處理返回重定向Request。
- 如果Request為空 則return response;
- 如果Request不為空 則再次進(jìn)入 while (true) 重新執(zhí)行realChain.proceed(即:進(jìn)行重定向進(jìn)行新的請求)
4.1 整個intercept方法的流程
- 整個方法的流程
- 構(gòu)建一個StreamAllocation對象,StreamAllocation相當(dāng)于是個管理類,維護(hù)了Connections、Streams和Calls之間的管理,該類初始化一個Socket連接對象,獲取輸入/輸出流對象。
- 繼續(xù)執(zhí)行下一個Interceptor,即BridgeInterceptor
- 拋出異常,則檢測連接是否還可以繼續(xù),以下情況不會重試
客戶端配置出錯不再重試
出錯后,request body不能再次發(fā)送
發(fā)生以下Exception也無法恢復(fù)連接
ProtocolException:協(xié)議異常
InterruptedIOException:中斷異常
SSLHandshakeException:SSL握手異常
SSLPeerUnverifiedException:SSL握手未授權(quán)異常
沒有更多線路可以選擇。- 根據(jù)響應(yīng)碼處理請求,返回Request不為空時則進(jìn)行重定向處理,重定向的次數(shù)不能超過20次。
4.2 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();
//1. 構(gòu)建一個StreamAllocation對象,StreamAllocation相當(dāng)于是個管理類,維護(hù)了
//Connections、Streams和Calls之間的管理,該類初始化一個Socket連接對象,獲取輸入/輸出流對象。
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
//重定向次數(shù)
int followUpCount = 0;
Response priorResponse = null;
//將前一步得到的followUp 賦值給request,重新進(jìn)入循環(huán),
while (true) {
if (canceled) {
//刪除連接上的call請求
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
//將前一步得到的followUp不為空進(jìn)入循環(huán) 繼續(xù)執(zhí)行下一步
//2. 繼續(xù)執(zhí)行下一個Interceptor,即BridgeInterceptor
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.
//嘗試通過路由進(jìn)行連接失敗。 該請求不會被發(fā)送
if (!recover(e.getLastConnectException(), streamAllocation, 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.
//嘗試與服務(wù)器通信失敗。 該請求可能已發(fā)送
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.
//構(gòu)建響應(yīng)體,這個響應(yīng)體的body為空。
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
Request followUp;
try {
// 根據(jù)響應(yīng)碼處理請求,返回Request不為空時則進(jìn)行重定向處理-拿到重定向的request
followUp = followUpRequest(response, streamAllocation.route());
} catch (IOException e) {
streamAllocation.release();
throw e;
}
if (followUp == null) {
if (!forWebSocket) {
streamAllocation.release();
}
return response;
}
closeQuietly(response.body());
//重定向的次數(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());
}
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,以便再次進(jìn)入循環(huán)執(zhí)行
request = followUp;
priorResponse = response;
}
}
4.3 followUpRequest拿到重定向的request
followUpRequest()
/**
* 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.
* 計算出HTTP請求響應(yīng)收到的userResponse響應(yīng)。
* 這將添加身份驗證標(biāo)頭,遵循重定向或處理客戶端請求超時。
* 如果后續(xù)措施不必要或不適用,則返回null。
*/
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) {
//407,代理認(rèn)證
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);
//401,未經(jīng)認(rèn)證
case HTTP_UNAUTHORIZED:
return client.authenticator().authenticate(route, userResponse);
//307,308
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"
//如果接收到307或308狀態(tài)碼以響應(yīng)除GET或HEAD以外的請求,則用戶代理絕不能自動重定向請求”
if (!method.equals("GET") && !method.equals("HEAD")) {
return null;
}
// fall-through
//300,301,302,303
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.
// url為null,不允許重定向
if (url == null) return null;
// If configured, don't follow redirects between SSL and non-SSL.
//查詢是否存在http與https之間的重定向
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
if (!sameScheme && !client.followSslRedirects()) return null;
// Most redirects don't include a request body.
//大多數(shù)重定向不包含請求體
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.
//在跨主機(jī)重定向時,請刪除所有身份驗證標(biāo)頭。 這對應(yīng)用程序?qū)觼碚f可能很煩人,因為他們無法保留它們。
if (!sameConnection(userResponse, url)) {
requestBuilder.removeHeader("Authorization");
}
return requestBuilder.url(url).build();
//408,超時
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.
//應(yīng)用程序?qū)又甘疚覀儾灰卦囌埱? 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;
}
}
5 StreamAllocation這個類的作用
- StreamAllocation這個類的作用
- 這個類協(xié)調(diào)了三個實體類的關(guān)系:
- Connections:連接到遠(yuǎn)程服務(wù)器的物理套接字,這個套接字連接可能比較慢,所以它有一套取消機(jī)制。
- Streams:定義了邏輯上的HTTP請求/響應(yīng)對,每個連接都定義了它們可以攜帶的最大并發(fā)流,HTTP/1.x每次只可以攜帶一個,HTTP/2每次可以攜帶多個。
- Calls:定義了流的邏輯序列,這個序列通常是一個初始請求以及它的重定向請求,對于同一個連接,我們通常將所有流都放在一個調(diào)用中,以此來統(tǒng)一它們的行為。
6
- 重定向功能默認(rèn)是開啟的,可以選擇關(guān)閉,然后去實現(xiàn)自己的重定向功能:
new OkHttpClient().newBuilder()
.followRedirects(false) //禁制OkHttp的重定向操作,我們自己處理重定向
.followSslRedirects(false)//https的重定向也自己處理