美文网首页
RetryAndFollowUpInterceptor源码分析

RetryAndFollowUpInterceptor源码分析

作者: 追风z | 来源:发表于2020-08-06 17:40 被阅读0次

    开头

    这个拦截器很容易从名字看出该拦截器是用来重试和处理http跳转的拦截器,所以看起来很简单,但是他逻辑可以说是相对复杂。下面就来看看。

    该拦截器用来接收失败和重定向的逻辑,同时还说了,Chrome浏览器最大支持21次跳转,Firefox,curl,wget支持20次,Safari支持16次,HTTP/1.0支持5次,所以该类取20次。可以从如下源码看出:

    private static final int MAX_FOLLOW_UPS = 20;
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            //向下转型成子类
            RealInterceptorChain realChain = (RealInterceptorChain) chain;
            Call call = realChain.call();
    
            //这里获取到EventListener,从他可以监听到Okhttp的执行流程
            EventListener eventListener = realChain.eventListener();
    
            //这里创建了一个StreamAllocation对,他内部处理创建流等操作,后面会分析
            //流:  Okhttp1.0是这样,但是2.0的话其实是建立了一个Socket连接,它里面可以创建多个流,这就是多路复用;Okhttp3在
            //Okhttp2中会有这种情况;  简单理解为一个流就是一个链接                        
            streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()),
                    call, eventListener, callStackTrace);
    
            int followUpCount = 0;//跳转的次数
            Response priorResponse = null;
            //这里开启一个循环,然后一直处理下面的事
            while (true) {//这是死循环
                if (canceled) {
                    //如果取消了,就关闭流,并抛出异常,退出循环
                    streamAllocation.release();
                    --> 这里的异常从方法intercept中抛出去了
                        也就是你取消链接后,onFailed方法中的那个异常是在这里抛出的
                    throw new IOException("Canceled");
                   
                }
    
                Response response = null;
                boolean releaseConnection = true;
                try {
                    //在这里调用下一个拦截器,获取结果,并在后续取处理他
                    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(), false, request)) {
                        不可恢复,就抛出异常
                        throw e.getLastConnectException();
                    }
                    //可恢复,这个连接也不释放
                    releaseConnection = false;
                    -->执行到这个continue,然后继续下一次循环,接着回到上面realChain.proceed调用拦截器链,直到抛出的额异常不能恢
                       复为止
                    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, requestSendStarted, request)) throw e;//如果不是,就抛出e
                    releaseConnection = false;
                     -->执行到这个continue,然后继续下一次循环,接着回到上面realChain.proceed调用拦截器链,直到抛出的额异常不能恢
                       复为止
                    continue;
                } finally {
                    // We're throwing an unchecked exception. Release any resources.
                    if (releaseConnection) {
                        //连接关闭的话(releaseConnection = true),会走ifl里面的diam
                        
                        //不管怎样,还需要释放使用过的流 
                         //表示这个流失败了,释放这个流
                        streamAllocation.streamFailed(null);
                        streamAllocation.release();
                    }
                }
    
                //将上一次的响应,添加到这次响应中
                if (priorResponse != null) {
                    response = response.newBuilder()
                            .priorResponse(priorResponse.newBuilder()
                                    .body(null)
                                    .build())
                            .build();
                }
    
                //判断是否符合跳转请求
                Request followUp = followUpRequest(response);
                //--点击跳转:followUpRequest 代码较多,下面查看
    
                if (followUp == null) {
                    //如果不需要跳转,并且不是socket,就释放流,并且返回response
                    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);
                } else if (streamAllocation.codec() != null) {
                    //如如果走到了这里,表示关闭流失败,需要抛出异常
                    throw new IllegalStateException("Closing the body of " + response
                            + " didn't close its backing stream. Bad interceptor?");
                }
    
                //将需要跳转的流,赋值给request,好下一次在请求
                //下面的response也是
                request = followUp;
                priorResponse = response;
            }
        }
    

    点击跳转

    --跳转:followUpRequest
    
        private Request  followUpRequest(Response userResponse) throws IOException {
            if (userResponse == null) throw new IllegalStateException();
            //
            Connection connection = streamAllocation.connection();
            Route route = connection != null
                    ? connection.route()
                    : null;
    
            //获取用户响应的code
            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
                    //http请求本身需要认证  前面使用的时候,用的就是这个(具体哪个,忘记了)
                    return client.authenticator().authenticate(route, userResponse);
    
                case HTTP_PERM_REDIRECT://307
                case HTTP_TEMP_REDIRECT://308
                    //这2个响应吗表示需要跳转
    
                    //
                    // "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")) {
                        //请求不是GET和HEAD,直接人会,因为如果是POST等请求是有风险的
                        return null;
                    }
                    //到这是需要跳转
                    // fall-through
                case HTTP_MULT_CHOICE:
                case HTTP_MOVED_PERM:
                case HTTP_MOVED_TEMP:
                case HTTP_SEE_OTHER:
                    //如果客户的不允许跳转,就直接返回
                    if (!client.followRedirects()) return null;
    
                    //获取到头部Location字段的值,他是需要跳转的url
                    String location = userResponse.header("Location");
                    if (location == null) return null;
                    //根据刚刚得到url,从新创建一个HttpUrl对象
                    //userResponse.request().url(): 用请求网络的时候的request中的url
                    //resolve(location):如果这location不能解析成一个网址,那么就是空的
                    HttpUrl url = userResponse.request().url().resolve(location);
    
                    //如果获取到的url为空,就直接返回
                    if (url == null) return null;
    
                    boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
                    //如果请求的的scheme不相同,并且客户的不予许https跳转,就返回
                    //client.followSslRedirects() 默认是true的 注意这里还有个!
                    if (!sameScheme && !client.followSslRedirects()) return null;
    
                    //根据上一次的request,从新构建一个Builder
                    Request.Builder requestBuilder = userResponse.request().newBuilder();
                    if (HttpMethod.permitsRequestBody(method)) {
                        //HttpMethod.permitsRequestBody(method):判断请求的方式比如POST等请求,通过源码可以看出
                        //这里可以不用去了解,可以简单看下
    
                        //这里主要处理一些WebDAV相关的
                        final boolean maintainBody = HttpMethod.redirectsWithBody(method);
                        //如果是get跳转,需要添加get请求体,如果是其他请求,需要将上一次的RequestBody带上
                        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");
                        }
                    }
    
                    //如果跳转的是不同的链接,需要移除所有的认证头
                    //因为把这个认证头,带过去的话,可能会有风险
                    if (!sameConnection(userResponse, url)) {
                        requestBuilder.removeHeader("Authorization");
                    }
    
                    //生成request
                    //前面:HttpUrl url = userResponse.request().url().resolve(location);获取到的url
                    //这里就是跳转的url创建的request(request里面包含了url)
                    return requestBuilder.url(url).build();
    
                case HTTP_CLIENT_TIMEOUT://408
                    //客户端超时
    
                    // 如果请求体不能再次请求,就直接返回
                    if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
                        return null;
                    }
    
                    //超时了,如果支持再次请求,就直接返回上次的请求体
                    return userResponse.request();
    
                default:
                    return null;
            }
        }
    
    
    -->点击跳转:sameConnection
    
        private boolean sameConnection(Response response, HttpUrl followUp) {
            HttpUrl url = response.request().url();
            //连接判断是否相同呢?
            //其实是判断url的主机名 端口 协议是否相同,相同就是相同的链接
            return url.host().equals(followUp.host())
                    && url.port() == followUp.port()
                    && url.scheme().equals(followUp.scheme());
        }
        
    -->点击跳转:createAddress
        private Address createAddress(HttpUrl url) {
            SSLSocketFactory sslSocketFactory = null;
            HostnameVerifier hostnameVerifier = null;
            CertificatePinner certificatePinner = null;
            if (url.isHttps()) {
                sslSocketFactory = client.sslSocketFactory();
                hostnameVerifier = client.hostnameVerifier();
                certificatePinner = client.certificatePinner();
            }
    
            //创建方式也很简答,就是将request,client上的一些信息封装为request
            //就是封装到Address 这样一个地址里面
            return new Address(url.host(), url.port(), client.dns(), client.socketFactory(),
                    sslSocketFactory, hostnameVerifier, certificatePinner, client.proxyAuthenticator(),
                    client.proxy(), client.protocols(), client.connectionSpecs(), client.proxySelector());
        }
    
    -->点击跳转:recover
      
       private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
            streamAllocation.streamFailed(e);
    
            // The application layer has forbidden retries.
            //默认是true  那么if条件是false,  就不会进入if里面, 那么往下走,是return true
            //if条件是false:表示是可以恢复错误的-->那么往下走,是return true,那么表示是可以恢复的
            if (!client.retryOnConnectionFailure()) return false;
    
            // We can't send the request body again.
            if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;
    
            // This exception is fatal.
            //-->点击跳转: isRecoverable
            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;
        }
        
    -->点击跳转:recover
        private boolean isRecoverable(IOException e, boolean requestSendStarted) {
            // If there was a protocol problem, don't recover.
            if (e instanceof ProtocolException) {
                //请求是一个协议异常,那么是不能恢复错误的,直接返回false
                return false;
            }
    
            // If there was an interruption don't recover, but if there was a timeout connecting to a route
            // we should try the next route (if there is one).
            if (e instanceof InterruptedIOException) {
                //InterruptedIOException: 服务端是终止的异常
                return e instanceof SocketTimeoutException && !requestSendStarted;
            }
    
            // Look for known client-side or negotiation errors that are unlikely to be fixed by trying
            // again with a different route.
            if (e instanceof SSLHandshakeException) {
                // If the problem was a CertificateException from the X509TrustManager,
                // do not retry.
                if (e.getCause() instanceof CertificateException) {
                    //是否是证书校验失败
                    //证书校验失败,无法恢复,直接返回false
                    return false;
                }
            }
            if (e instanceof SSLPeerUnverifiedException) {
                // e.g. a certificate pinning error.
                return false;
            }
    
            // An example of one we might want to retry with a different route is a problem connecting to a
            // proxy and would manifest as a standard IOException. Unless it is one we know we should not
            // retry, we return true and try a new route.
            return true;
        }
    

    相关文章

      网友评论

          本文标题:RetryAndFollowUpInterceptor源码分析

          本文链接:https://www.haomeiwen.com/subject/vugzrktx.html