系统学习详见OKhttp源码解析详解系列
1 http协议中的重定向
- client:向server发送一个请求,要求获取一个资源
- server:接收到这个请求后,发现请求的这个资源实际存放在另一个位置于是server在返回的response header的Location字段中写入那个请求资源的正确的URL,并设置reponse的状态码为30x
- client:接收到这个response后,发现状态码为重定向的状态吗,就会去解析到新的URL,根据新的URL重新发起请求
2 状态码
- 重定向最常用为301,也有303,
- 临时重定向用302,307
3 与请求转发的对比
- 请求转发
- 服务器在处理request的过程中将request先后委托多个servlet或jsp接替进行处理的过程,request和reponse始终在期间传递
- 区别
- 重定向时,客户端发起两次请求,而请求转发时,客户端只发起一次请求
- 重定向后,浏览器地址栏url变成第二个url,而请求转发没有变(请求转发对于客户端是透明的)
- 流程
重定向:
用户请求-----》服务器入口-------》组件------>服务器出口-------》用户----(重定向)---》新的请求
请求转发
用户请求-----》服务器入口-------》组件1---(转发)----》组件2------->服务器出口-------》用户
4 RetryAndFollowUpInterceptor拦截器
RetryAndFollowUpInterceptor负责失败重试以及重定向。
RetryAndFollowUpInterceptor的作用就是处理了一些连接异常以及重定向。
4.0 重定向流程
- 第一次请求返回response,followUpRequest根据响应码处理返回重定向Request。
- 如果Request为空 则return response;
- 如果Request不为空 则再次进入 while (true) 重新执行realChain.proceed(即:进行重定向进行新的请求)
4.1 整个intercept方法的流程
- 整个方法的流程
- 构建一个StreamAllocation对象,StreamAllocation相当于是个管理类,维护了Connections、Streams和Calls之间的管理,该类初始化一个Socket连接对象,获取输入/输出流对象。
- 继续执行下一个Interceptor,即BridgeInterceptor
- 抛出异常,则检测连接是否还可以继续,以下情况不会重试
客户端配置出错不再重试
出错后,request body不能再次发送
发生以下Exception也无法恢复连接
ProtocolException:协议异常
InterruptedIOException:中断异常
SSLHandshakeException:SSL握手异常
SSLPeerUnverifiedException:SSL握手未授权异常
没有更多线路可以选择。- 根据响应码处理请求,返回Request不为空时则进行重定向处理,重定向的次数不能超过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. 构建一个StreamAllocation对象,StreamAllocation相当于是个管理类,维护了
//Connections、Streams和Calls之间的管理,该类初始化一个Socket连接对象,获取输入/输出流对象。
StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
createAddress(request.url()), call, eventListener, callStackTrace);
this.streamAllocation = streamAllocation;
//重定向次数
int followUpCount = 0;
Response priorResponse = null;
//将前一步得到的followUp 赋值给request,重新进入循环,
while (true) {
if (canceled) {
//删除连接上的call请求
streamAllocation.release();
throw new IOException("Canceled");
}
Response response;
boolean releaseConnection = true;
try {
//将前一步得到的followUp不为空进入循环 继续执行下一步
//2. 继续执行下一个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.
//尝试通过路由进行连接失败。 该请求不会被发送
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.
//尝试与服务器通信失败。 该请求可能已发送
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.
//构建响应体,这个响应体的body为空。
if (priorResponse != null) {
response = response.newBuilder()
.priorResponse(priorResponse.newBuilder()
.body(null)
.build())
.build();
}
Request followUp;
try {
// 根据响应码处理请求,返回Request不为空时则进行重定向处理-拿到重定向的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());
//重定向的次数不能超过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,以便再次进入循环执行
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请求响应收到的userResponse响应。
* 这将添加身份验证标头,遵循重定向或处理客户端请求超时。
* 如果后续措施不必要或不适用,则返回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,代理认证
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,未经认证
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状态码以响应除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.
//大多数重定向不包含请求体
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();
//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.
//应用程序层指示我们不要重试请求
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这个类的作用
- 这个类协调了三个实体类的关系:
- Connections:连接到远程服务器的物理套接字,这个套接字连接可能比较慢,所以它有一套取消机制。
- Streams:定义了逻辑上的HTTP请求/响应对,每个连接都定义了它们可以携带的最大并发流,HTTP/1.x每次只可以携带一个,HTTP/2每次可以携带多个。
- Calls:定义了流的逻辑序列,这个序列通常是一个初始请求以及它的重定向请求,对于同一个连接,我们通常将所有流都放在一个调用中,以此来统一它们的行为。
6
- 重定向功能默认是开启的,可以选择关闭,然后去实现自己的重定向功能:
new OkHttpClient().newBuilder()
.followRedirects(false) //禁制OkHttp的重定向操作,我们自己处理重定向
.followSslRedirects(false)//https的重定向也自己处理