美文网首页
Okhttp3 Interceptor(三)

Okhttp3 Interceptor(三)

作者: coding400 | 来源:发表于2020-05-13 22:02 被阅读0次
    interceptor.png

    前言

    OkHttp 中的 Interceptor 是通过责任链模式来设计的, 责任链模式参考: 责任链模式 , 至于为什么需要使用该模式, 我的理解是一次完整的请求需要以下步骤

    1. 构建业务请求数据
    2. 自定义公共 Header 数据
    3. 建立 Socket 连接
    4. 发送请求
    5. 缓存请求数据

    那么对每一个步骤来讲, 它是按照处理逻辑进行排序, 并且每一个处理步骤都代表相应的职责,通常来讲,编写代码时不会将所有的逻辑都放到一堆去写, 因为当需要增添其他功能时将是巨大的灾难,,这时责任链模式将派上巨大用场。

    Interceptor 介绍

    Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls

    如官网所称, Interceptors 是一个强大的机制, 可以用来 监控、重写 request 、 重试等 。

    在 Okhttp 中,拦截器同样起到非常重要的作用,通过提供的默认拦截器来实现了:建立连接、发送请求、处理响应等,其中 Interceptor 又根据使用场景划分为 Application Interceptor 和 Network Interceptor ,Application Interceptor 是用来在整个 okhttp client 应用处理请求期间起作用且只被执行一次,而 Network Interceptor 则是在 okhttp client 应用处理请求期间中的每一次网络交互都会执行一次(因为有重试策略,所以可能会出现处理一次应用的请求需要多次网络重试)。那么根据其场景可以选择不同类型拦截器进行增强。

      public class ApplicationLogInterceptor implements Interceptor {
    
        @Override
        public Response intercept(Chain chain) throws IOException {
          Request request = chain.request();
          long start = System.currentTimeMillis();
          Response response = chain.proceed(request);
          long end = System.currentTimeMillis();
          if (end - start > 300) {
            System.out.println(String.format("request cost time exceed=%s ms", end - start));
          }
          return response;
        }
      }
    
        OkHttpClient httpClient = new OkHttpClient.Builder()
            .callTimeout(500, TimeUnit.MILLISECONDS)
            .connectTimeout(500, TimeUnit.MILLISECONDS)
            .addInterceptor(new ApplicationLogInterceptor())
            .build();
    

    通过实现 okhttp3.Interceptor 的 intercept 来达到对请求增强的目的,然后利用 OkHttpClient.Builder 的 addInterceptor(Interceptor interceptor)方法,将应用拦截器的引用共享给 OkHttpClient 客户端,这里与顶部图片的 OkHttp Core 上半部分相同。如果需要使用网络拦截器,只需要将OkHttpClient.Builder 的 addInterceptor 方法换成 addNetworkInterceptor 即可。

    注意这里的拦截器对所有请求都是属于共享的,因此所有类变量使用不当将会导致线程不安全,如果必须让每个拦截器有“状态”,那么可以通过 ThreadLocal 来实现

    Okhttp Core 中 默认拦截器

    Okhttp 将 http request 所经过的每次请求链路的功能划分给按职责划分到不同拦截器中,最终通过拦截器链 RealInterceptorChain 来组织,完成一次又一次的请求与响应

      Response getResponseWithInterceptorChain() throws IOException {
        // Build a full stack of interceptors.
        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.addAll(client.interceptors());
        interceptors.add(retryAndFollowUpInterceptor);
        interceptors.add(new BridgeInterceptor(client.cookieJar()));
        interceptors.add(new CacheInterceptor(client.internalCache()));
        interceptors.add(new ConnectInterceptor(client));
        if (!forWebSocket) {
          interceptors.addAll(client.networkInterceptors());
        }
        interceptors.add(new CallServerInterceptor(forWebSocket));
    
        Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
            originalRequest, this, eventListener, client.connectTimeoutMillis(),
            client.readTimeoutMillis(), client.writeTimeoutMillis());
    
        Response response = chain.proceed(originalRequest);
        if (retryAndFollowUpInterceptor.isCanceled()) {
          closeQuietly(response);
          throw new IOException("Canceled");
        }
        return response;
      }
    

    在 RealCall 的 getResponseWithInterceptorChain() 方法中可以看到,在执行请求前,需要默认的拦截器和业务自定义的拦截器添加到 interceptors 之后,最终交给 RealInterceptorChain 来调度 (突然想到 国不可一日无君,家不可一日无主)

    1. RetryAndFollowUpInterceptor

    负责对请求进行重试处理,前提是没有在 OkHttpClient.Builder 中设置 .retryOnConnectionFailure(false),默认是 true ,并且重试 21 次, google 浏览器也是这个策略,而 Http1.1 则是推荐 5 次,没办法改重试的次数,只有你把它 ban 了,然后自己写个应用拦截器,具体看 RetryAndFollowUpInterceptor 源码

         while (true) {
          if (canceled) {
            streamAllocation.release();
            throw new IOException("Canceled");
          }
    
          Response response;
          boolean releaseConnection = true;
          try {
            response = realChain.proceed(request, streamAllocation, null, null);
            releaseConnection = false;
          } catch (RouteException e) {
            ...... 省略
          } catch (IOException e) {
            ...... 省略
          } finally {
            ...... 省略
          }
    ....
    

    这里可以看到 RouteException 和 IOException 这两种异常的情况才有机会重试

    1. BridgeInterceptor

    BridgeInterceptor负责在request阶段对请求头添加一些字段,在response阶段对响应进行一些gzip解压操作

      @Override 
      public Response intercept(Chain chain) throws IOException {
        Request userRequest = chain.request();
        Request.Builder requestBuilder = userRequest.newBuilder();
    
        RequestBody body = userRequest.body();
        if (body != null) {
          MediaType contentType = body.contentType();
          if (contentType != null) {
            requestBuilder.header("Content-Type", contentType.toString());
          }
    
          long contentLength = body.contentLength();
          if (contentLength != -1) {
            requestBuilder.header("Content-Length", Long.toString(contentLength));
            requestBuilder.removeHeader("Transfer-Encoding");
          } else {
            requestBuilder.header("Transfer-Encoding", "chunked");
            requestBuilder.removeHeader("Content-Length");
          }
        }
    ...... 省略
       // 处理响应数据
        Response networkResponse = chain.proceed(requestBuilder.build());
    
        HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers());
    
        Response.Builder responseBuilder = networkResponse.newBuilder()
            .request(userRequest);
    
        if (transparentGzip
            && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
            && HttpHeaders.hasBody(networkResponse)) {
          GzipSource responseBody = new GzipSource(networkResponse.body().source());
          Headers strippedHeaders = networkResponse.headers().newBuilder()
              .removeAll("Content-Encoding")
              .removeAll("Content-Length")
              .build();
          responseBuilder.headers(strippedHeaders);
          String contentType = networkResponse.header("Content-Type");
          responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
        }
    
        return responseBuilder.build();
    ...... 省略
    
    1. CacheInterceptor

    缓存服务的请求与响应

    1. ConnectInterceptor

    创建一个新的连接,或从连接池服用连接

    1. CallServerInterceptor

    这是拦截器链中的最后的拦截器,使用 ConnectInterceptor 的连接来向目标服务器发送网络请求,并读取解析 Response 数据流

    相关文章

      网友评论

          本文标题:Okhttp3 Interceptor(三)

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