OkHttp的重定向及重试拦截器的源码解读

OkHttp拦截器链源码解读传送门://www.greatytc.com/p/1181f48d6dcf
RetryAndFollowUpInterceptor这个类在OkHttp请求当中充当重定向及重试拦截的角色;

/**
 * This interceptor recovers from failures and follows redirects as necessary. It may throw an
 * {@link IOException} if the call was canceled.
 * 重定向和网络请求失败重试的拦截器,上面注释中说到如果取消会引起IO流异常
 */
public final class RetryAndFollowUpInterceptor implements Interceptor {
    /**
     * How many redirects and auth challenges should we attempt? Chrome follows 21 redirects; Firefox,
     * curl, and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5.
     */
    private static final int MAX_FOLLOW_UPS = 20; // 失败的网络请求重连最大次数

    private final OkHttpClient client;
    private final boolean forWebSocket; // 是否使用WebSocket进行拦截
    private volatile StreamAllocation streamAllocation; // 建立创建Http请求的一些网络组件
    private Object callStackTrace;
    private volatile boolean canceled;

    public RetryAndFollowUpInterceptor(OkHttpClient client, boolean forWebSocket) {
        this.client = client;
        this.forWebSocket = forWebSocket;
    }

// 拦截进行重定向
@Override 
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        RealInterceptorChain realChain = (RealInterceptorChain) chain;
        Call call = realChain.call();
        EventListener eventListener = realChain.eventListener();

        // 建立创建Http请求的一些网络组建
        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) {
                streamAllocation.release(); // 把连接上的call请求释放掉
                throw new IOException("Canceled"); // 抛出取消Io流异常
            }

            Response response;
            boolean releaseConnection = true;
            try {
                // proceed 内部会实现下一个拦截器链的方法 这个在上一篇已经分析过了
                // 将前一步得到的followUp不为空进入循环 继续执行下一步 followUp就是request
                // 继续执行下一个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.getFirstConnectException();
                }
                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;
            }

           // followUp 就是followUpRequest方法经过检测返回的Request
            if (followUp == null) {
                streamAllocation.release();
                return response; // 如果Request为空 则return response;
            } else {
                // 如果Request不为空 则再次进入 while (true) 重新执行
            }

            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; // 把重定向的请求赋值给request,以便再次进入循环执行
            priorResponse = response;
        }
    }

重定向功能的逻辑在followUpRequest方法,followUpRequest会拿到重定向的request

/**
     * 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) {
            case HTTP_PROXY_AUTH: // 407 代理认证
                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: // 401 未经认证
                return client.authenticator().authenticate(route, userResponse);

            case HTTP_PERM_REDIRECT:  // 308
            case HTTP_TEMP_REDIRECT:  // 307 临时重定向
                // "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
            case HTTP_MULT_CHOICE: // 300 多种选择
            case HTTP_MOVED_PERM:  // 301 永久移动到新的Url
            case HTTP_MOVED_TEMP:  // 302 暂时重定向
            case HTTP_SEE_OTHER:   // 303 查看其他地址和301有点类似
                // 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();

            case HTTP_CLIENT_TIMEOUT: // 408 超时
                // 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()) { // 这里就可以看出,在创建调用OkHttp的时候可以设置不进行重定向
                    // 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: // 503 服务不可用
                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;
        }
    }

从上面可以看出重定向功能默认是开启的,可以选择关闭,然后去实现自己的重定向功能

new OkHttpClient.Builder()
                .followRedirects(false)  //禁制OkHttp的重定向操作,我们自己处理重定向
                .followSslRedirects(false)//https的重定向也自己处理

总结一下重定向拦截器的流程:
1.构建一个StreamAllocation对象
2.调用RealInterceptorChain.proceed(.....)进行网络请求
3.根据异常结果或者响应结果判断是否要进行重新请求
4.调用下一个拦截器,即BridgeInterceptor,对response进行处理,返回给上一个拦截器

PS:抛出异常,在以下情况下是不会重试的

  1. 客户端配置出错不再重试,因为出错后,request body不能再次发送
  2. ProtocolException:协议异常
  3. InterruptedIOException:中断异常
  4. SSLHandshakeException:SSL握手异常
  5. SSLPeerUnverifiedException:SSL握手未授权异常
  6. 没有更多线路可以选择
    7.根据响应码处理请求,返回Request不为空时则进行重定向处理,重定向的次数超过20次,因为在这个一开始成员变量中做了限制,失败的网络请求重连最大次数是20。

上面还用到了一个类StreamAllocation,它维护了Connections、Streams和Calls之间的管理,该类初始化一个Socket连接对象,获取输入/输出流对象。但是你会发现StreamAllocation在RetryAndFollowUpInterceptor只做了一些取消、释放资源等操作,并没有真正的去执行网络连接,这是因为这一步操作是在拦截器ConnectInterceptor中使用,所以这里先不去详细阅读,等分析到ConnectInterceptor拦截器的时候在深入阅读。

谢谢阅读,如有错误,欢迎指正。

OkHttp的桥拦截器的源码解读传送门://www.greatytc.com/p/20bfab62c3cd

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,204评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,091评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,548评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,657评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,689评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,554评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,302评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,216评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,661评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,851评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,977评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,697评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,306评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,898评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,019评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,138评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,927评论 2 355

推荐阅读更多精彩内容