系列文章
OKHttp原始碼解析(2)----攔截器RetryAndFollowUpInterceptor
OKHttp原始碼解析(3)----攔截器BridgeInterceptor
OKHttp原始碼解析(4)----攔截器CacheInterceptor
OKHttp原始碼解析(5)----攔截器ConnectInterceptor
OKHttp原始碼解析(6)----攔截器CallServerInterceptor
1.簡介
This interceptor recovers from failures and follows redirects as necessary. It may throw an {@link IOException} if the call was canceled.
重試與重定向攔截器,負責重試及重定向
2.原始碼解析
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
streamAllocation = new StreamAllocation(
client.connectionPool(), createAddress(request.url()), callStackTrace);
int followUpCount = 0;
Response priorResponse = null;
while (true) {
if (canceled) {
streamAllocation.release();
throw new IOException("Canceled");
}
Response response = null;
boolean releaseConnection = true;
try {
response = ((RealInterceptorChain) chain).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 are 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 = followUpRequest(response);
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()), callStackTrace);
} 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;
}
}
複製程式碼
重試重定向攔截器,用於對網路請求的結果進行分析,並對若干失敗的請求結果進行重試和重定向。其中,判斷是否重試重定向的邏輯在方法followUpRequest(Response userResponse)中:
/**
* 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.
*/
private Request followUpRequest(Response userResponse) throws IOException {
if (userResponse == null) throw new IllegalStateException();
Connection connection = streamAllocation.connection();
Route route = connection != null
? connection.route()
: null;
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;
//location為重定向所需的多個URL,從中可以解析出url
String location = userResponse.header("Location");
if (location == null) return null;
HttpUrl url = userResponse.request().url().resolve(location);
// Do not follow redirects to unsupported protocols.
if (url == null) return null;
// If configured, do not follow redirects between SSL and non-SSL.
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
if (!sameScheme && !client.followSslRedirects()) return null;
// Most redirects do not 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:
// 408s 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 (userResponse.request().body() instanceof UnrepeatableRequestBody) {
return null;
}
return userResponse.request();
default:
return null;
}
}
複製程式碼
在followUpRequest方法中,對HTTP Status-Code進行判定,並對client進行修改,以完成重定向過程。
String location = userResponse.header("Location");
HttpUrl url = userResponse.request().url().resolve(location);
複製程式碼
重定向所需的url都在location中,需要從中解析出來。
重定向的重新請求,是通過while(true)迴圈來不斷進行的,直到請求成功、達到最大重試次數(20次)或其他異常等。
需要重定向的HTTP Status-Code
- 300: Multiple Choices. 被請求的資源有一系列可供選擇的回饋資訊,每個都有自己特定的地址和瀏覽器驅動的商議資訊。使用者或瀏覽器能夠自行選擇一個首選的地址進行重定向。
- 301: Moved Permanently.被請求的資源已永久移動到新位置,並且將來任何對此資源的引用都應該使用本響應返回的若干個 URI 之一
- 302: Temporary Redirect.請求的資源現在臨時從不同的 URI 響應請求。
- 303: See Other.對應當前請求的響應可以在另一個 URI 上被找到,而且客戶端應當採用 GET 的方式訪問那個資源。
- 307:Temporary Redirect臨時重定向(請求是get或head方法時才可重定向)
- 308:Permanent redirect永久重定向(請求是get或head方法時才可重定向)
- 401: Unauthorized.當前請求需要使用者驗證。
- 407: Proxy Authentication Required.與401響應類似,只不過客戶端必須在代理伺服器上進行身份驗證。
- 408: Request Time-Out.請求超時。
注意:
- 2XX系列:代表請求已成功被伺服器接收、理解、並接受
- 3XX系列:代表需要客戶端採取進一步的操作才能完成請求,這些狀態碼用來重定向,後續的請求地址(重定向目標)在本次響應的 Location 域中指明。
- 4XX系列:表示請求錯誤
- 5XX系列:代表了伺服器在處理請求的過程中有錯誤或者異常狀態發生