安卓开源框架学习|OKHttp原理讲解之RetryAndFollowUpInterceptor

一、前言: 1.1 本篇主要讲解内容
1.RetryAndFollowUpInterceptor中主要成员介绍
2.拦截器中重试机制
3.拦截器中执行流程

1.2 OKHttp项目地址:
https://github.com/square/okhttp

1.3 OKHttp系列讲解简介:
OKHttp项目本身还是很大的,而且涉及到的知识点很多,所以一篇文章是很难概括全的,所以会以一个系列文章的方式来详细讲解OKHttp。
系列准备写以下几篇。
OKHttp原理讲解之基本概念_失落夏天的博客-CSDN博客
OKHttp原理讲解之责任链模式及扩展_失落夏天的博客-CSDN博客
OKHttp原理讲解之重试拦截器(预计03.22发布)
OKHttp原理讲解之路由拦截器
OKHttp原理讲解之缓存拦截器
OKHttp原理讲解之连接池拦截器
OKHttp原理讲解之请求拦截器
PS:预计每周更新1-2篇的进度进行

二、主要成员介绍 Route:路由。当我们请求一个服务的时候,中间要经过DNS域名解析返回多个IP供我们去尝试连接。并且中间有可能会经过多层的DNS,
【安卓开源框架学习|OKHttp原理讲解之RetryAndFollowUpInterceptor】StreamAllocation:StreamAllocation在其注释中写道,主要是协调Connections,Streams和Call之间的关系。
StreamAllocation中包含几个主要的对象,如下:
ConnectionPool:连接池,具体会在ConnectInterceptor那一章细讲。一个请求结束后,并不会立马关闭连接,还可以利用这个socket继续进行数据的传输。
Address:请求地址的封装对象。
Call:请求体
EventListener:监听对象,方便监听状态
RouteSelector:路由选择器。我们请求一个服务的时候,中间要经过DNS域名解析返回多个

三、RetryAndFollowUpInterceptor中重试机制 3.1重试机制 这里的重试机制我感觉设计的是特别的巧妙的。首先外层是一个while(true)循环,然后发送请求,如果返回值有问题或者抛出异常,则消耗一次重试次数,如果没有超过重试次数上限,则在进行一遍循环发送请求。
如果当次请求成功,并且如果进行了通讯(没有使用缓存),则通过 streamAllocation.release(); 关闭和释放此次的链接和资源。
如果失败,也要关闭响应中的数据流。

//代码3.1 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) { ... //代码3.2 continue; } catch (IOException e) { ... continue; } finally { ... } ... Request followUp = followUpRequest(response, streamAllocation.route()); 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; }

3.2 如何判断是否请求成功? 即使请求成功,也不一定真的发送了请求,因为还存在命中缓存的可能。所以这需要综合的判断,在拦截器中,判断方法在followUpRequest方法中。
这里的设计是很巧妙的,如果followUpRequest方法返回的request不为空,则代表请求失败,下一次请求使用如果该方法返回值followUp不为空,则代表此次结果是OK的。否则下一次请求就是这一次的返回值followUp。
另外我们详细看代码,发现这个判断方法里面竟然没有我们所常知的200,404,这是为何呢?
我们可以看上面的代码段3.2,这里进行了异常捕获,其实原理就在这里。如果是404错误,那么会在后续的迭代器中直接抛出异常,而在3.2处进行了捕获。所以就不会执行到后面的followUpRequest方法当中。
那如果是200成功呢?如果reponseCode=200的话,则会走到代码3.3的逻辑,直接返回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) { 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: //代码3.3 return null; } }



    推荐阅读