Android - 剖析OKHttp(5)- 拦截器BridgeInterceptor

·  阅读 50

源码分析基于 3.14.4

BridgeInterceptor作用

主要负责请求头的填充以及Response的解压;

//BridgeInterceptor类中
 @Override public Response intercept(Chain chain) throws IOException {
    if (body != null) {//1
      MediaType contentType = body.contentType();
      if (contentType != null) {
        requestBuilder.header("Content-Type", contentType.toString());
      }
      long contentLength = body.contentLength();
      ......
      requestBuilder.header("Content-Length", Long.toString(contentLength));
    }
    if (userRequest.header("Host") == null) {//2
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }
    if (userRequest.header("Connection") == null) {//3
      requestBuilder.header("Connection", "Keep-Alive");
    }
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {//4
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    }
    ......
    if (userRequest.header("User-Agent") == null) {//5
      requestBuilder.header("User-Agent", Version.userAgent());
    }
    Response networkResponse = chain.proceed(requestBuilder.build());//6
    ......
    if (transparentGzip
        && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding"))
        && HttpHeaders.hasBody(networkResponse)) {//7
      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();
  }
复制代码
  • 核心处理在BridgeInterceptor.intercept函数中;
  • 注释1:如果有请求body,则加入Content-Type、Content-Length属性;
  • 注释2:如果没有设置Host,则配置;
  • 注释3:如果没有配置Connection,则配置Keep-Alive长连接;
  • 注释4:如果不是分段下载,则配置gzip,表示服务器可以压缩传输;
  • 注释5:配置User-Agent为okhttp/3.14.4;
  • 注释6:调用下一个拦截器;
  • 注释7:处理结果,如果Response是压缩的,则用GzipSource进行解压,结果返回给上一个拦截器;

总结:

  • BridgeInterceptor负责添加请求头,例如Content-Type、Content-Length、Host、Keep-Alive、gzip;
  • BridgeInterceptor负责对Response进行解压,结果返回给上一个拦截器;

以上分析有不对的地方,请指出,互相学习,谢谢哦!

分类:
Android
标签:
分类:
Android
标签:
收藏成功!
已添加到「」, 点击更改