Okhttp之RetryAndFollowUpInterceptor拦截器分析

Okhttp的浅层架构分析
Okhttp的责任链模式和拦截器分析
Okhttp之RetryAndFollowUpInterceptor拦截器分析
Okhttp之BridgeInterceptor拦截器分析
Okhttp之CacheInterceptor拦截器分析
Okhttp之ConnectInterceptor拦截器分析
Okhttp之网络连接相关三大类RealConnection、ConnectionPool、StreamAllocation
前面了解了拦截器是怎么互相配合调用的,这篇文章来逐个看看各个原生拦截器做的具体工作。
先来看看RetryAndFollowUpInterceptor(重试和跟随拦截器):

    @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;
        //这个while循环是它的亮点
        while (true) {
            if (canceled) {
                //请求被取消了,删除连接上的call请求
                streamAllocation.release();
                throw new IOException("Canceled");
            }

            Response response;
            boolean releaseConnection = true;
            try {
                //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.
                //尝试通过路由进行连接失败。 该请求不会被发送,直接抛异常
                //recover()方法就是判断当前是否是一些致命异常或者违规的情况,从而决定是否要重试
                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);
               //抛出Io异常,不继续重试
                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为空。注意这个response是从服务器拿回来的然后重新构建的
            if (priorResponse != null) {
                response = response.newBuilder()
                        .priorResponse(priorResponse.newBuilder()
                                .body(null)
                                .build())
                        .build();
            }

            Request followUp;
            try {
                // 根据响应码处理请求,返回Request不为空时则进行重定向处理-拿到重定向的request
                //followUpRequest()方法就是分析返回的response是什么情况,要执行什么样的重试策略,这个方法后面会详细解析
                followUp = followUpRequest(response, streamAllocation.route());
            } catch (IOException e) {
                streamAllocation.release();
                throw e;
            }
            //为空则直接返回response,没必要重试了
            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);
            }
              //不可重复的请求body,抛异常
            if (followUp.body() instanceof UnrepeatableRequestBody) {
                streamAllocation.release();
                throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
            }
            //不一样的Connection,重新赋值一下,重定向后可能改变了url
            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,以便再次进入循环执行,达到重试的目的
            request = followUp;
            priorResponse = response;
        }
    }

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;
        }
    }
总结RetryAndFollowUpInterceptor的工作流程:
1.构建一个StreamAllocation对象,StreamAllocation相当于是个管理类,维护了Connections、Streams和Calls之间的管理,该类初始化一个Socket连接对象,获取2.输入/输出流对象。
2.继续执行下一个Interceptor,即BridgeInterceptor得到http返回的response,扑捉这个过程中的异常,抛出异常,则检测连接是否还可以继续,以下情况不会重试
  • 客户端配置出错不再重试
  • 出错后,request body不能再次发送
  • 发生以下Exception也无法恢复连接
  • ProtocolException:协议异常
  • InterruptedIOException:中断异常
  • SSLHandshakeException:SSL握手异常
  • SSLPeerUnverifiedException:SSL握手未授权异常
  • 没有更多线路可以选择。
3.根据响应码处理请求,判断返回的code是哪种情况,进而进行相应的重试操作,否则不进行重试,直接返回http拿到的response,另外,重定向的次数不能超过20次。

你可能感兴趣的:(Okhttp之RetryAndFollowUpInterceptor拦截器分析)