RetryAndFollowUpInterceptor拦截器分析

上篇文章讲解了OKHttp的基本流程后,我们来看下RetryAndFollowUpInterceptor(错误重试和重定向拦截器)的实现。

不多说,我们直接看下该拦截器的intercept方法:

 public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Call call = realChain.call();
    EventListener eventListener = realChain.eventListener();

    // 构建StreamAllocation对象,传入连接池、地址,Call对象等
    StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(),
            createAddress(request.url()), call, eventListener, callStackTrace);
    this.streamAllocation = streamAllocation;

    // 重定向次数
    int followUpCount = 0;
    Response priorResponse = null;
    // 开启一个while循环
    while (true) {
        // 判断是否已经cancel,如果已经cancel,则释放streamAllocation并抛出异常
        if (canceled) {
            streamAllocation.release(true);
            throw new IOException("Canceled");
        }

        Response response;
        boolean releaseConnection = true;
        try {
            // 通过调用RealInterceptorChain的proceed方法来调用下一个拦截器的intercept,并返回执行结果response
            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(true);
            }
        }

        // Attach the prior response if it exists. Such responses never have a body.
        // priorResponse为保存上一次的需要重定向时的response对象,放入到当前的response对象中,在followUpRequest重定向处理时用作判断
        if (priorResponse != null) {
            response = response.newBuilder()
                    .priorResponse(priorResponse.newBuilder()
                            .body(null)
                            .build())
                    .build();
        }

        Request followUp;
        try {
            // 重定向处理,不进行重定向则返回null
            followUp = followUpRequest(response, streamAllocation.route());
        } catch (IOException e) {
            streamAllocation.release(true);
            throw e;
        }

        if (followUp == null) {
            // 不进行重定向,释放资源
            streamAllocation.release(true);
            // 返回response
            return response;
        }

        // 需要进行重定向操作,关闭流
        closeQuietly(response.body());

        // 判断重定向次数次数是否大于重定向次数(20),如果大于,则释放资源并抛出异常
        if (++followUpCount > MAX_FOLLOW_UPS) {
            streamAllocation.release(true);
            throw new ProtocolException("Too many follow-up requests: " + followUpCount);
        }

        // 实现了UnrepeatableRequestBody,流类型,不能被缓存,所以不能重试
        if (followUp.body() instanceof UnrepeatableRequestBody) {
            streamAllocation.release(true);
            throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
        }

        // 判断是否是同一个http请求,如果不是,则重新创建个StreamAllocation对象
        if (!sameConnection(response, followUp.url())) {
            streamAllocation.release(false);
            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;
    }
}

整理下该拦截器的执行流程:

1、构建了StreamAllocation对象,该对象的作用是协调连接、流和Calls对象(请求)三者之间的关系。
2、开启了一个while循环,判断请求是否被取消,如果取消,则抛出异常。
3、调用下一个拦截器的intercept(BridgeInterceptor),并返回执行结果response。
4、在返回response期间发生异常,则判断是否可以进行错误重试(recover方法),如果可以重试,则重新执行以上流程。
5、如果请求成功返回了response对象,则判断当前是否需要进行重定向,如果不需要,则释放资源,返回response对象。
6、如果需要重定向,则判断重定向次数是否丹玉最大可重定向次数和判断请求实体是否是UnrepeatableRequestBody类型,如果是,则抛出异常停止循环。
7、再判断重定向的url和请求url是否是同一个请求,如果不是,则重新创建个StreamAllocation对象。
8、最后重新给request等赋值,重新执行以上流程。

分析

我们看下调用下一个拦截器的逻辑:

// 通过调用RealInterceptorChain的proceed方法来调用下一个拦截器的intercept,并返回执行结果response
response = realChain.proceed(request, streamAllocation, null, null);
releaseConnection = false;

需要提下,RealInterceptorChain的request、streamAllocation等这几个属性在拦截器的调用过程中会逐个进行初始化,而这里会传入刚构建完成的streamAllocation。

接下来我们看下当抛出异常时,判断是否可错误重试(recover)的方法

private boolean recover(IOException e, StreamAllocation streamAllocation,
                            boolean requestSendStarted, Request userRequest) {
    streamAllocation.streamFailed(e);

    // The application layer has forbidden retries.
    // 是否禁止连接失败重试,可在应用调用层通过修改retryOnConnectionFailure变量来控制,默认retryOnConnectionFailure为true
    if (!client.retryOnConnectionFailure()) return false;

    // We can't send the request body again.
    // 请求已经发送且请求的body是StreamedRequestBody类型(实现了UnrepeatableRequestBody,数据没有被缓存,只能传输一次),则不能重试
    if (requestSendStarted && requestIsUnrepeatable(e, userRequest)) return false;

    // This exception is fatal.
    // 如果这是个致命的错误(如协议问题、IO中断异常、SSL握手异常等),则不可重试
    if (!isRecoverable(e, requestSendStarted)) return false;

    // No more routes to attempt.
    // 没有更多的路由可以尝试
    if (!streamAllocation.hasMoreRoutes()) return false;

    // For failure recovery, use the same route selector with a new connection.
    return true;
}

可以看到,不能进行重试的情况有:在应用层设置了禁止重试、请求实体是StreamedRequestBody类型、没有路由可切换或协议问题等严重错误。

接下来看下对重定向处理的流程:

 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_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"
            if (!method.equals("GET") && !method.equals("HEAD")) {
                return null;
            }
            // fall-through
        case HTTP_MULT_CHOICE: // 300
        case HTTP_MOVED_PERM: // 301
        case HTTP_MOVED_TEMP: // 302
        case HTTP_SEE_OTHER: // 303
            // Does the client allow redirects?
            // 应用层是否允许重定向
            if (!client.followRedirects()) return null;

            String location = userResponse.header("Location"); // 取出重定向url
            if (location == null) return null;
            // 解析出重定向url
            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.
            // 判断重定向的url和原先请求的url的scheme是否一致
            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,请求超时,符合条件后会进行重试
           
            if (!client.retryOnConnectionFailure()) { // 判断应用层是否手动设置了禁止重试
                return null;
            }

            // 判断是否实现了UnrepeatableRequestBody
            if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
                return null;
            }

            if (userResponse.priorResponse() != null
                    && userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
                return null;
            }

            // 取出请求头中的Retry-After(表示用户代理需要等待多长时间之后才能继续发送请求),如果有延时重试时间,则不自动重试
            if (retryAfter(userResponse, 0) > 0) {
                return null;
            }

            // 重试
            return userResponse.request();
    }
}

该方法如果返回null,则表示不进行重定向,反之,则可以进行重定向。
首先根据返回的状态码来处理不同的情况,我们直接看状态码为重定向那部分的处理。

1、先判断当前在应用层是否禁用了重定向,默认允许进行重定向。
2、然后从请求头(Location)中取出重定向url,判断重定向的url和请求的url的scheme是否一致,如果不一致,则返回null。
3、对请求实体的处理,然后通过requestBuilder重新构建request并返回。

获得经过重定向处理的request,如果request为null,则释放资源并返回response。否则,则进行以下判断:

 // 判断重定向次数次数是否大于重定向次数(20),如果大于,则释放资源并抛出异常
 if (++followUpCount > MAX_FOLLOW_UPS) {
     streamAllocation.release(true);
     throw new ProtocolException("Too many follow-up requests: " + followUpCount);
 }

 // 实现了UnrepeatableRequestBody,流类型,不能被缓存,所以不能重试
 if (followUp.body() instanceof UnrepeatableRequestBody) {
     streamAllocation.release(true);
     throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
 }

 // 判断是否是同一个http请求,如果不是,则重新创建个StreamAllocation对象
 if (!sameConnection(response, followUp.url())) {
     streamAllocation.release(false);
     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等进行赋值,重新进入循环并执行以上流程。

总结

该拦截器的作用和它的名字一样,就是处理错误重试和重定向。在处理返回response的过程中,如果发生了异常,那就判断当前是否可以进行重试操作,如果可以,则重新进入循环。当请求成功并返回response对象后,则通过当前状态码和一些配置判断否可以进行重定向,如果可以,则利用重定向的url重新构建request,重新进入循环执行。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值