美文网首页
2、okhttp源码解析-拦截器RetryAndFllowUpI

2、okhttp源码解析-拦截器RetryAndFllowUpI

作者: 飞奔的口罩 | 来源:发表于2020-08-19 17:43 被阅读0次

    1、okhttp源码解析-整体流程
    2、okhttp源码解析-拦截器RetryAndFllowUpInterceptor
    3、okhttp源码解析-拦截器BridgeInterceptor
    4、okhttp源码解析-拦截器CacheInterceptor
    5、okhttp源码解析-拦截器ConnectInterceptor
    6、okhttp源码解析-拦截器CallServerInterceptor
    7、okhttp源码解析-Dispatcher任务管理器

    RetryAndFllowUpInterceptor

    这个拦截器主要用于重试连接、重定向等处理。   
    1、处理401/407状态码,补充Authorization,重试连接
        - 401:
        服务端发送WWW-Authenticate,
        表示需要clent传Authorization信息头。
        - 407:
        与401响应类似,只不过客户端必须在代理服务器上进行身份验证。  
        代理服务器必须返回一个 Proxy-Authenticate 用以进行身份询问。
        客户端可以返回一个 Proxy-Authorization 信息头用以验证
    2、处理408,网络连接超时,重试连接。
    3、处理30*状态码,重定向。
    4、尝试连接次数最大数:20
    
    为什么是20次尝试,代码注释的解释:
    //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;
    
    

    1.流程示意图

    RetryAndFllowUpInterceptor.png

    2.代码思路

    • 1、获取责任链返回的response结果。
    response = realChain.proceed(request, streamAllocation, null, null);
    
    • 2、判断上次循环的response(priorResponse)是否为空,不为空,说明连接已完成,直接生成response。
    if (priorResponse != null) {
    response = response.newBuilder()
        .priorResponse(priorResponse.newBuilder()
                .body(null)
                .build())
        .build();
    }
    
    • 3、获取需要重连的Request,followUp。如果followUp为空说明无须重试连接。不为空继续循环,重试连接。
    Request followUp = followUpRequest(response);
    
    if (followUp == null) {
        if (!forWebSocket) {
          streamAllocation.release();
        }
        return response;
    }
    
    • 4.1整体方法说明
    
      @Override public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        int followUpCount = 0;
        Response priorResponse = null;
        //开始循环
        while (true) {
          ...
          // 获取责任链的结果,response
            response = realChain.proceed(request, streamAllocation, null, null);
            releaseConnection = false;
          ...
    
          // Attach the prior response if it exists. Such responses never have a body.
          // 上次循环后设置的priorResponse,不为空直接创建response。
          if (priorResponse != null) {
            response = response.newBuilder()
                .priorResponse(priorResponse.newBuilder()
                        .body(null)
                        .build())
                .build();
          }
    
          Request followUp = followUpRequest(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);
          }
            ...
    
          request = followUp;
          priorResponse = response;
        }
      }
    
    • 4.2followUpRequest()方式实现。
      • 处理401、407需要Authorization的情况,并返回Request,重试连接。
      • 处理408,请求超时情况。并返回Request,重试连接
      • 处理30*,重定向情况。并返回Request,重试连接。
      • 其他情况视为通过,直接返回null,结束重试。
     private Request followUpRequest(Response userResponse) throws IOException {
        int responseCode = userResponse.code();
    
        final String method = userResponse.request().method();
        switch (responseCode) {
        // 401 服务器请求Authorization认证。
        // 服务端发送WWW-Authenticate,
        // 表示需要clent传Authorization信息头。
          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);
        //407 代理服务器Authorization认证
        // 代理服务器必须返回一个 Proxy-Authenticate // 用以进行身份询问。
        // 客户端可以返回一个 Proxy-Authorization
          case HTTP_UNAUTHORIZED:
            return client.authenticator().authenticate(route, userResponse);
        //30* 重定向处理
          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();
    
        // 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;
            }
    
            return userResponse.request();
    
        //默认情况,直接返回null,结束重试循环
          default:
            return null;
        }
      }
    

    相关文章

      网友评论

          本文标题:2、okhttp源码解析-拦截器RetryAndFllowUpI

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