Android - 剖析OKHttp(4)- 拦截器Bridge

2020-11-09  本文已影响0人  杨0612

源码分析基于 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();
  }

总结:

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

上一篇下一篇

猜你喜欢

热点阅读