OKHttp——拦截器源码分析整理

OKHttp 源码解析(二)拦截器 上一篇解读了OKHttp 的基本框架源码,其中 OKHttp 发送请求的核心是调用构建拦截器链,遍历拦截器,执行请求,执行完成时返回结果。这篇看一下 OKHttp 的拦截器链。本文查看 OKHttp 源码的版本是 3.4.2.OkHttp 允许开发者自定义拦截器并优先执行开发者定义的拦截器。具体做法如下定义拦截器实现 OkHttp 的拦截器接口// ... } } // 官网解释:观察、修改并潜在地短路发出的请求和返回的相应响应。// 通常,拦截器会添加、删除或转换请求或响应的标头。 阅读详情

getResponseWithInterceptorChain()

  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());

    return chain.proceed(originalRequest);
  }

从源码中可以看出 经过层层list内的Interceptor拦截之后,组装成一个Response返回。

Interceptor

public interface Interceptor {
  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();
    //分发处理
    Response proceed(Request request) throws IOException;

    Connection connection();
  }
}

Chain是拦截器发生的主要接口。

所有的拦截器

  • RetryAndFollowUpInterceptor——这个拦截器主要是做重试,网络错误,以及重定向的一些操作。
  • BridgeInterceptor——主要将用户的请求转换为网络的请求,负责对Request和Response报文进行加工。
  • CacheInterceptor——缓存拦截器
  • ConnectIntercepter——连接拦截器,主要是处理连接服务器,以及http,https的包装
  • CallServerInterceptor——服务拦截器,主要是发送、读取数据,是拦截器的最后一个环节。

RealInterceptorChain的责任链模式通过层层拦截进而完成组装okhttp的拦截功能。

责任链

  Response getResponseWithInterceptorChain() throws IOException {
    //省略
    Interceptor.Chain chain = new RealInterceptorChain(
        interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
  }

getResponseWithInterceptorChain()通过new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest)方式实现了拦截器的第一次初始化操作。

  public RealInterceptorChain(List<Interceptor> interceptors, StreamAllocation streamAllocation,
      HttpCodec httpCodec, RealConnection connection, int index, Request request) {
    this.interceptors = interceptors;
    this.connection = connection;
    this.streamAllocation = streamAllocation;
    this.httpCodec = httpCodec;
    this.index = index;
    this.request = request;
  }

  //注意这个多态方法
  @Override public Response proceed(Request request) throws IOException {
    return proceed(request, streamAllocation, httpCodec, connection);
  }


  public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException {
//忽略部分代码
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

//忽略部分代码
    }

    return response;
  }

其中:

proceed()调用自己的构造器通过index+1创建下一个拦截器,然后接着调用interceptor.intercept(next),下一个拦截器接着又会调用chain.proceed(networkRequest),往复下去,实现链式调用排好的构造器。

那么子类又如何将返回值回传给父类呢?

proceed(Request request)和proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection)这两个多态方法,因为不同的拦截器会回调不同的方法。我们也就可以知道不同的参数在不同的拦截器中得到了初始化。

RetryAndFollowUpInterceptor

@Override public Response intercept(Chain chain) throws IOException {
 //忽略部分代码
response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
//回调RealInterceptorChain的proceed方法!注意此地的参数是四个值,streamAllocation在此地被赋值

 //忽略部分代码
}

BridgeInterceptor

 @Override public Response intercept(Chain chain) throws IOException {
    //忽略部分代码
    Response networkResponse = chain.proceed(requestBuilder.build());
    注意此地RealInterceptorChain的proceed方法!注意此地的参数是一个,

    //回调RealInterceptorChain的proceed方法
    //忽略部分代码
}

CacheInterceptor

@Override public Response intercept(Chain chain) throws IOException {
  //忽略部分代码
 networkResponse = chain.proceed(networkRequest);
  注意此地RealInterceptorChain的proceed方法!注意此地的参数是一个

 //忽略部分代码
}

ConnectInterceptor

@Override public Response intercept(Chain chain) throws IOException {
 //忽略部分代码
 return realChain.proceed(request, streamAllocation, httpCodec, connection); 
  注意此地RealInterceptorChain的proceed方法!注意此地的参数是四个,httpCodec, connection在此得到赋值。

 }

CallServerInterceptor

 @Override public Response intercept(Chain chain) throws IOException {
 //忽略部分代码
    return response;
}

CallServerInterceptor之前的拦截器均调用了相关的realChain.proceed方法进行一个链式的组装。

RetryAndFollowUpInterceptor

public final class RetryAndFollowUpInterceptor implements Interceptor {

	······
	
  @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    streamAllocation = new StreamAllocation(
        // 三个参数分别对应:(1)全局的连接池,(2)连接线路Address, (3)堆栈对象
        client.connectionPool(), createAddress(request.url()), callStackTrace);

    int followUpCount = 0;
    Response priorResponse = null;
    while (true) {
      if (canceled) {
        streamAllocation.release();
        throw new IOException("Canceled");
      }

      Response response = null;
      boolean releaseConnection = true;
      try {
        //  执行下一个拦截器,即BridgeInterceptor
        // RealInterceptorChain会将初始化好的连接对象传递给下一个拦截器,也是贯穿整个请求的对象,在拦截器执行过程中,的几个属性字段会一步一步赋值
        response = ((RealInterceptorChain) chain).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.
         //  如果有异常,判断是否要恢复
        if (!recover(e.getLastConnectException(), false, request)) {
          throw e.getLastConnectException();
        }
        releaseConnection = false;
        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;
        releaseConnection = false;
        continue;
      } finally {
        // We're throwing an unchecked exception. Release any resources.
        if (releaseConnection) {
          streamAllocation.streamFailed(null);
          streamAllocation.release();
        }
      }

      // Attach the prior response if it exists. Such responses never have a body.
      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());
       // 是否超过最大限制
      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()), callStackTrace);
      } else if (streamAllocation.codec() != null) {
        throw new IllegalStateException("Closing the body of " + response
            + " didn't close its backing stream. Bad interceptor?");
      }

      request = followUp;
      priorResponse = response;
    }
  }
	······
	
  /**
   * Report and attempt to recover from a failure to communicate with a server. Returns true if
   * {@code e} is recoverable, or false if the failure is permanent. Requests with a body can only
   * be recovered if the body is buffered or if the failure occurred before the request has been
   * sent.
   */
  private boolean recover(IOException e, boolean requestSendStarted, Request userRequest) {
    streamAllocation.streamFailed(e);
    // 1. 应用层配置不在连接,默认为true
    // The application layer has forbidden retries.
    if (!client.retryOnConnectionFailure()) return false;
    // 2. 请求Request出错不能继续使用
    // We can't send the request body again.
    if (requestSendStarted && userRequest.body() instanceof UnrepeatableRequestBody) return false;
    //  是否可以恢复的
    // This exception is fatal.
    if (!isRecoverable(e, requestSendStarted)) return false;
    // 4. 没用更多线路可供选择
    // No more routes to attempt.
    if (!streamAllocation.hasMoreRoutes()) return false;

    // For failure recovery, use the same route selector with a new connection.
    return true;
  }

  1.应用层配置不在连接(默认为true),则不可恢复
  2.请求Request是不可重复使用的Request,则不可恢复
  3.根据Exception的类型判断是否可以恢复的 (isRecoverable()方法)
    3.1、如果是协议错误(ProtocolException)则不可恢复
    3.2、如果是中断异常(InterruptedIOException)则不可恢复
    3.3、如果是SSL握手错误(SSLHandshakeException && CertificateException)则不可恢复
    3.4、certificate pinning错误(SSLPeerUnverifiedException)则不可恢复
  4.没用更多线路可供选择 则不可恢复
  如果上述条件都不满足,则这个request可以恢复

  private boolean isRecoverable(IOException e, boolean requestSendStarted) {
    // If there was a protocol problem, don't recover.
    if (e instanceof ProtocolException) {
      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) {
      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) {
        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;
  }

  /**
   * Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
   * either add authentication headers, follow redirects or handle a client request timeout. If a
   * follow-up is either unnecessary or not applicable, this returns null.
   */
  private Request followUpRequest(Response userResponse) throws IOException {
    if (userResponse == null) throw new IllegalStateException();
    Connection connection = streamAllocation.connection();
    Route route = connection != null
        ? connection.route()
        : null;
    int responseCode = userResponse.code();

    final String method = userResponse.request().method();
    switch (responseCode) {
      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);

      case HTTP_UNAUTHORIZED:
        return client.authenticator().authenticate(route, userResponse);

      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();

      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 (userResponse.request().body() instanceof UnrepeatableRequestBody) {
          return null;
        }

        return userResponse.request();

      default:
        return null;
    }
  }

  /**
   * Returns true if an HTTP request for {@code followUp} can reuse the connection used by this
   * engine.
   */
  private boolean sameConnection(Response response, HttpUrl followUp) {
    HttpUrl url = response.request().url();
    return url.host().equals(followUp.host())
        && url.port() == followUp.port()
        && url.scheme().equals(followUp.scheme());
  }
}

顺着上面的源码,我们梳理一下intercept的整体流程:

  • 根据url创建Address对象,实例化StreamAllocation
  • 开启while(true)循环
  • 检测是否取消
  • 执行下一个拦截器BridgeInterceptor
  • 如果发生异常,在catch里面判断是否继续请求
  • 如果priorResponse不为空,则说明前面已经获取到了相应
  • 结合获取的Response和先前的Response调用followUpRequest检查相应是否需要重定向,如果不需要则返回当前请求
  • 重定向次数+1,同时判断是否达到最大限制数量。
  • 检查是否有相同的链接,是:释放,重新创建
  • 重新设置request,并把当前的Response保存到priorResponse,继续while循环

BridgeInterceptor

这个类主要完成:

  • 从应用层数据类型到网络层数据类型的转换,将我们的javaBean放进报文内
  • cookie处理
  • Gzip转码
public final class BridgeInterceptor implements Interceptor {
  private final CookieJar cookieJar;

  public BridgeInterceptor(CookieJar cookieJar) {
    this.cookieJar = cookieJar;
  }

  @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");
      }
    }

    if (userRequest.header("Host") == null) {
      requestBuilder.header("Host", hostHeader(userRequest.url(), false));
    }

    if (userRequest.header("Connection") == null) {
      requestBuilder.header("Connection", "Keep-Alive");
    }


    //如果我们不自定义编解码方式的方式,默认使用Gzip的编解码
    // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing
    // the transfer stream.
    boolean transparentGzip = false;
    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
      transparentGzip = true;
      requestBuilder.header("Accept-Encoding", "gzip");
    }
    //在创建ohHttpClient的时候,添加的cookiejar。
    List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url());
    if (!cookies.isEmpty()) {
      requestBuilder.header("Cookie", cookieHeader(cookies));
    }

    if (userRequest.header("User-Agent") == null) {
      requestBuilder.header("User-Agent", Version.userAgent());
    }

    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);
      responseBuilder.body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)));
    }

    return responseBuilder.build();
  }

//从前面okHttpClient 中设置的cookieJar,然后设置到请求头的Cookie中去。
  /** Returns a 'Cookie' HTTP request header with all cookies, like {@code a=b; c=d}. */
  private String cookieHeader(List<Cookie> cookies) {
    StringBuilder cookieHeader = new StringBuilder();
    for (int i = 0, size = cookies.size(); i < size; i++) {
      if (i > 0) {
        cookieHeader.append("; ");
      }
      Cookie cookie = cookies.get(i);
      cookieHeader.append(cookie.name()).append('=').append(cookie.value());
    }
    return cookieHeader.toString();
  }
}

CacheInterceptor

CacheInterceptor主要完成了:根据报文CacheControl、Cache等内容结合本地的缓存控制策略进行缓存处理

public final class CacheInterceptor implements Interceptor {
  final InternalCache cache;

  public CacheInterceptor(InternalCache cache) {
    this.cache = cache;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    //1. 读取候选缓存;
    Response cacheCandidate = cache != null
        ? cache.get(chain.request())
        : null;

    long now = System.currentTimeMillis();
    //2. 创建缓存策略(强制缓存,对比缓存等策略);
    CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();
    Request networkRequest = strategy.networkRequest;
    Response cacheResponse = strategy.cacheResponse;

    if (cache != null) {
      cache.trackResponse(strategy);
    }

    if (cacheCandidate != null && cacheResponse == null) {
      closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it.
    }

    // If we're forbidden from using the network and the cache is insufficient, fail.
     //根据策略,不使用网络,缓存又没有直接报错;
    if (networkRequest == null && cacheResponse == null) {
      return new Response.Builder()
          .request(chain.request())
          .protocol(Protocol.HTTP_1_1)
          .code(504)
          .message("Unsatisfiable Request (only-if-cached)")
          .body(Util.EMPTY_RESPONSE)
          .sentRequestAtMillis(-1L)
          .receivedResponseAtMillis(System.currentTimeMillis())
          .build();
    }
    // 4. 根据策略,不使用网络,有缓存就直接返回;
    // If we don't need the network, we're done.
    if (networkRequest == null) {
      return cacheResponse.newBuilder()
          .cacheResponse(stripBody(cacheResponse))
          .build();
    }

    Response networkResponse = null;
    try {
      // 5. 前面个都没有返回,走下一个拦截器;
      networkResponse = chain.proceed(networkRequest);
    } finally {
      // If we're crashing on I/O or otherwise, don't leak the cache body.
      if (networkResponse == null && cacheCandidate != null) {
        closeQuietly(cacheCandidate.body());
      }
    }
    //6. 接收到的网络结果,如果是code 304, 使用缓存,返回缓存结果(对比缓存)
    // If we have a cache response too, then we're doing a conditional get.
    if (cacheResponse != null) {
      if (networkResponse.code() == HTTP_NOT_MODIFIED) {
        Response response = cacheResponse.newBuilder()
            .headers(combine(cacheResponse.headers(), networkResponse.headers()))
            .sentRequestAtMillis(networkResponse.sentRequestAtMillis())
            .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis())
            .cacheResponse(stripBody(cacheResponse))
            .networkResponse(stripBody(networkResponse))
            .build();
        networkResponse.body().close();

        // Update the cache after combining headers but before stripping the
        // Content-Encoding header (as performed by initContentStream()).
        cache.trackConditionalCacheHit();
        cache.update(cacheResponse, response);
        return response;
      } else {
        closeQuietly(cacheResponse.body());
      }
    }
     //7. 读取网络结果;
    Response response = networkResponse.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .networkResponse(stripBody(networkResponse))
        .build();
     //8. 对数据进行缓存;
    if (cache != null) {
      if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {
        // Offer this request to the cache.
        CacheRequest cacheRequest = cache.put(response);
        return cacheWritingResponse(cacheRequest, response);
      }

      if (HttpMethod.invalidatesCache(networkRequest.method())) {
        try {
          cache.remove(networkRequest);
        } catch (IOException ignored) {
          // The cache cannot be written.
        }
      }
    }

    return response;
  }

ConnectInterceptor

这个拦截器主要完成了与后台建立连接完成通信前的准备工作

public final class ConnectInterceptor implements Interceptor {
  public final OkHttpClient client;

  public ConnectInterceptor(OkHttpClient client) {
    this.client = client;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    StreamAllocation streamAllocation = realChain.streamAllocation();

    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpCodec httpCodec = streamAllocation.newStream(client, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }
}

CallServerInterceptor

这个拦截器主要完成了:连接搭建后真正的通信操作,利用okio进行流式的传递。

public final class CallServerInterceptor implements Interceptor {
  private final boolean forWebSocket;

  public CallServerInterceptor(boolean forWebSocket) {
    this.forWebSocket = forWebSocket;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    HttpCodec httpCodec = realChain.httpStream();   
    //HttpCodec用来读写数据

    StreamAllocation streamAllocation = realChain.streamAllocation();
    RealConnection connection = (RealConnection) realChain.connection();
    Request request = realChain.request();

    long sentRequestMillis = System.currentTimeMillis();
    //写入请求头
    httpCodec.writeRequestHeaders(request);

    Response.Builder responseBuilder = null;
    if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
      // If there's a "Expect: 100-continue" header on the request, wait for a "HTTP/1.1 100
      // Continue" response before transmitting the request body. If we don't get that, return what
      // we did get (such as a 4xx response) without ever transmitting the request body.
      if ("100-continue".equalsIgnoreCase(request.header("Expect"))) {
        httpCodec.flushRequest();
        responseBuilder = httpCodec.readResponseHeaders(true);
      }
       //写入请求体
      if (responseBuilder == null) {
        // Write the request body if the "Expect: 100-continue" expectation was met.
        Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength());
        BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
        request.body().writeTo(bufferedRequestBody);
        bufferedRequestBody.close();
      } else if (!connection.isMultiplexed()) {
        // If the "Expect: 100-continue" expectation wasn't met, prevent the HTTP/1 connection from
        // being reused. Otherwise we're still obligated to transmit the request body to leave the
        // connection in a consistent state.
        streamAllocation.noNewStreams();
      }
    }

    httpCodec.finishRequest();
    //读取响应头
    if (responseBuilder == null) {
      responseBuilder = httpCodec.readResponseHeaders(false);
    }

    Response response = responseBuilder
        .request(request)
        .handshake(streamAllocation.connection().handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build();
    //读取响应体
    int code = response.code();
    if (forWebSocket && code == 101) {
      // Connection is upgrading, but we need to ensure interceptors see a non-null response body.
      response = response.newBuilder()
          .body(Util.EMPTY_RESPONSE)
          .build();
    } else {
      response = response.newBuilder()
          .body(httpCodec.openResponseBody(response))
          .build();
    }

    if ("close".equalsIgnoreCase(response.request().header("Connection"))
        || "close".equalsIgnoreCase(response.header("Connection"))) {
      streamAllocation.noNewStreams();
    }

    if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
      throw new ProtocolException(
          "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
    }

    return response;
  }
}

总结

在这里插入图片描述
在这里插入图片描述

  • RetryAndFollowUpInterceptor ——它是一个负责失败重连的拦截器。它是 Okhttp 内置的第一个拦截器,通过 while (true) 的死循环来进行对异常结果或者响应结果判断是否要进行重新请求。
  • BridgeInterceptor——为用户构建的一个 Request 请求转化为能够进行网络访问的请求,同时将网络请求回来的响应 Response 转化为用户可用的 Response。比如,涉及的网络文件的类型和网页的编码,返回的数据的解压处理等等。
  • CacheInterceptor—— 根据 OkHttpClient 对象的配置以及缓存策略对请求值进行缓存。
  • ConnectInterceptor—— 负责与服务器建立 Socket 连接,并且创建了一个 HttpStream 它包括通向服务器的输入流和输出流。
  • CallServerInterceptor——使用 HttpStream 与服务器进行数据的读写操作的。
OKHttp3源码分析——学习笔记 文章目录1. HttpClient与HttpUrlConnection的区别2. OKHttp源码分析使用步骤:dispatcher任务调度器,Request请求RealCallAsyncCall3. OKHttp架构分析1. 异步请求线程池, Dispather2. 连接池清理线程池- ConnectionPool3. 缓存整理线程池 DisLruCache4. Http2异步事务线程池, ht... 阅读详情

相关推荐

从零开始:手把手教你检查并更新英伟达GPU驱动和CUDA版本(Windows/Linux双平台)

本文详细指导如何在Windows和Linux系统上检查并更新英伟达GPU驱动和CUDA版本,解决版本不匹配导致的常见问题。涵盖驱动更新、CUDA Toolkit安装、版本冲突排解及性能优化技巧,帮助开发者高效管理GPU计算环境。

weixin_29237635的博客 701

OKHttp源码3:拦截器

从上面的代码可以看出了,先获取原请求头,然后在请求中添加请求头,然后在根据需求,决定是否要填充Cookie,在对原始请求做出处理后,使用chain的procced方法得到响应,接下来对响应做处理得到用户响应,最后返回响应。关于连接拦截器更多的内容,可以看下一篇博客,okHttp的网络操作部分。这里我们只是做一个简单的分析并不深入其中,我们继续来看下一个拦截器。即CallServerInterceptor拦截器。

weixin_50961942的博客 1158

实验六 存储器实验

只读存储器(ROM)是一种在正常工作时其存储的数据固定不变,其中的数据只能读出,不能写入,即使断电也能够保留数据,要想在只读存储器中存入或改变数据,必须具备特定的条件。当地址为00000101时,会分别在数据位宽为8,16,32的只读寄存器中找到地址为00000101所对应的十进制地址位置,也就是地址为5的数据,并将其分别以8位,16位,32位输出。因此,输出保持为0。因此,当异步清零信号为1时,无论其他输入信号是什么,触发器的输出都会被强制清零,输出为0。1)寄存器输入0011,使能端1,异步清零0。

wenmou1111的博客 3001

Android OkHttp源码分析--拦截器

本拦截器是整个责任链中的第一个,这意味着它会是首次接触到 Request 与最后接收到 Response 的角色,在这个 拦截器中主要功能就是判断是否需要重试与重定向。重试的前提是出现了 RouteException 或者 IOException。一但在后续的拦截器执行过程中出现这两个异常,就会 通过 recover 方法进行判断是否进行连接重试。

sziitjin的博客 1157

港口集装箱码头运营FlexSim仿真

列队4中的集装箱会根据不同类型的集装箱会放置在不同的堆场,因此根据前面对集装箱设置的标签Type的数值不同,设置不同的发送端口。集装箱到达列队3后,会有70%的集装箱到达堆场,30%的集装箱运出港口,因此在Queue列队3的Flow界面设置按照百分比发送端口,其中70%发送到端口1,即发送到列队4等待进入堆场,30%发送到端口2,即发送至出闸口。通过上述对比表格可以看出,当集卡数量在10的时候,岸桥和场桥的设备利用率达到了最高,当集卡数量为12的时候场桥1和场桥3的利用率有所下降,因此综合考虑。

m0_72514516的博客 1331

Bellhop水声信道模型的仿真

Bellhop是一种基于射线追踪的水声信道模型,广泛用于预测水下环境中的声压场。它通过模拟声波在水中的传播路径,计算声场分布,适用于复杂的水下通信场景。

yt94832的博客 1312

OkHttp3源码详解之拦截器(四),你所不知道的Android原生开发的现状

实际是创建一个RealCall实际就是讲一个RealCall从代码中可以看到最终RealCall被转化成一个AsyncCall并被放入到任务队列中,任务队列中的分发逻辑这里先不说,相关实现会放在疑问进行介绍。execute方法的逻辑并不复杂,简单的说就是:调用getResponseWithInterceptorChain获取服务器返回通知任务分发器(client.dispatcher)该任务已结束。

2301_78416573的博客 1077

uniapp [全端兼容] - 实现全景图Vr 720°全景效果查看预览功能,3D全景图流畅不卡顿渲染+手势拖拽+悬浮工具按钮,uniAPP实现vr看720度全景效果示例代码(H5小程序APP全兼容)

uniapp显示720度全景图,720°全景图显示,在h5中展示720°全景图,浏览全景图,基于uniApp实现vr全景预览,加载全景图,uni-app全景预览插件,UNI-APP实现3D全景图,实现720°全景图展示,uniapp全景视频播放,uniapp项目实现vr720度全景图片预览,在网页上展示760全景图片和视频,全景图场景切换,UNIAPP全景VR图,uniapp加载720全景图_uniapp怎么加载vr图片,uniapp实现vr全景看房,uni-app实现全景效果,加载很慢卡怎么办,实现全景预

🏆 前端领域优质创作者 1万+

OKhttp源码分析

OKhttp源码分析 前言:本篇博客将对OKhttp的重点代码和框架流程进行分析,重点是对OKhttp的连接器链进行深入理解,同时文末将对整个流程进行总结提炼。 概述: OKhttp拦截器(interceptor)是OKhttp网络请求框架的精髓所在,通过框架对拦截器的逐个调用实现了高效灵活的网络请求,首先放一张图让大家对拦截器链有一个认识吧: 代码分析: 下面从一个最简单的网络请求开始分析OKhttp整个请求过程 String url = "http://wwww.baidu.com";

居家小男的博客 235

【007】C++编程必知:原码、补码、反码的全面解读

计算机存储的是数据的补码。原码:计算机中对数字的二进制定点表示方法。比如123的原码是0111 1011。无符号数:原码=反码=补码。有符号数:要分正数和负数,正数的最高位为0,负数的最高位为1。其中,正数的原码、反码、补码都是相同的;负数的反码等于原码的符号数(最高位)不变,其他位取反;补码等于反码+1。比如:-123的原码是1111 1011,反码为1000 0100,补码为1000 0101。原码、补码和反码都是用于计算机表示有符号整数的方法。

Lion_Long的博客 2918

论文翻译:arxiv-2023 Do-Not-Answer: A Dataset for Evaluating Safeguards in LLMs

随着大型语言模型(LLMs)的快速发展,出现了新的、难以预测的有害能力。这要求开发者能够通过评估“危险能力”来识别风险,以便负责任地部署LLMs。在这项工作中,我们收集了第一个开源数据集,用于评估LLMs中的安全保障,并以低成本部署更安全的开源LLMs。我们的数据集经过策划和筛选,只包含负责任的语言模型不应遵循的指令。我们注释并评估了六个流行的LLMs对这些指令的响应。基于我们的注释,我们继续训练了几个类似BERT的分类器,并发现这些小型分类器在自动安全评估上能够取得与GPT-4相当的成果。

CSPhD-winston的博客 1131

OkHttp3源码详解(三) 拦截器,android基础面试题

Override从代码中可以看到最终RealCall被转化成一个AsyncCall并被放入到任务队列中,任务队列中的分发逻辑这里先不说,相关实现会放在疑问进行介绍。这里只需要知道AsyncCall的excute方法最终将会被执行:try {} else {} else {execute方法的逻辑并不复杂,简单的说就是:调用getResponseWithInterceptorChain获取服务器返回。

601

【图像超分】论文精读:Residual Dense Network for Image Super-Resolution(RDN)

一个非常深的卷积神经网络 (CNN) 最近在图像分类 (SR) 方面取得了巨大成功,并提供了分层特征。然而,大多数基于深度 CNN 的 SR 模型没有充分利用原始低分辨率 (LR) 图像中的层次特征,从而实现相对较低的性能。在本文中,我们提出了一种新的残差密集网络(RDN)来解决图像SR中的这个问题。我们充分利用所有卷积层的分层特征。具体来说,我们提出了残差密集块(RDB)通过密集连接的卷积层提取丰富的局部特征。RDB 进一步允许将前一个 RDB 的状态与当前 RDB 的所有层直接连接,从而产生连续的内存

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 7256

OkHttp3源码详解(三) 拦截器,PDF超过6000页,

希望大家能有一个好心态,想进什么样的公司要想清楚,并不一定是大公司,我选的也不是特大厂。当然如果你不知道选或是没有规划,那就选大公司!希望我们能先选好想去的公司再投或内推,而不是有一个公司要我我就去!还有就是不要害怕,也不要有压力,平常心对待就行,但准备要充足。最后希望大家都能拿到一份满意的 offer!如果目前有一份工作也请好好珍惜好好努力,找工作其实挺累挺辛苦的。这里附上上述的面试题相关的几十套字节跳动,京东,小米,腾讯、头条、阿里、美团等公司19年的面试题。

m0_60721649的博客 880

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

最新阿里Android高级面试题及答案,OkHttp3源码详解(三) 拦截器(1),android开发基础有哪些

id移动开发、AIGC大模型、C C#、Go语言、Java、Linux运维、云计算、MySQL、PMP、网络安全、Python爬虫、UE5、UI设计、Unity3D、Web前端开发、产品经理、车载开发、大数据、鸿蒙、计算机网络、嵌入式物联网、软件测试、数据结构与算法、音视频开发、Flutter、IOS开发、PHP开发、.NET、安卓逆向、云计算**只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

2401_84002482的博客 775

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

okhttp3 源码解析笔记整理——同步、异步请求

1、同步请求 okhttp 可以使用 RealCall # execute() 方法来进行一个同步的请求。 try { Response response = mOkHttpClient.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); } RealCall # execute()...

一个有思想的搬运工 546

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

OkHttp3源码分析

重点 本文打算从三点来剖析OkHttp3: * 网络请求的整理流程-会使用 * 拦截器模式-易扩展 * 缓存和连接池-高性能 整体流程 我们在阅读某一类源码之前,首先要学会怎么使用,其次才是去了解内部的实现原理,实现方案上有什么技巧。 okhttp的一张流程图: 官方用例 get使用方式 OkHttpClient client = new OkHttpCli...

K-night的专栏 4507

Android OKHttp

自学了视频的内容,整理成笔记,方便查阅和复习。 OKHttp简介GET请求POST请求OKHttp_Utils 简介OKHttp 使用 Utils 的 GET 请求文本OKHttp 使用 Utils 的 POST 请求文本OKHttp 使用 Utils下载大文件OKHttp 使用 Utils 进行文件的上传OKHttp 使用 Utils 请求单张图片OKHttp 其他封装库OKHttp 源码分析 ...

weixin_39492854的博客 534

Okhttp文件上传源码分析

okhttp文件传输的源码分析

红旺永福 1468

5.okhttp

简单使用 OkHttpClient client = new OkHttpClient.Builder() .build(); Request request = new Request.Builder() .url(ENDPOINT) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Overri

只影的博客 440

android 闹钟源码分析_Android网络编程-OKHttp源码角度分析Http

前面介绍了网络的基础知识,这篇主要从OKHttp源码角度来分析Http。OKHttp是一个优秀的网络请求框架,有以下特点:支持HTTP2/SPDYSocket自动选择最好路线,并支持自动重连拥有自动维护的Socket连接池,减少握手次数拥有队列线程池,轻松写并发拥有Interceptors轻松处理请求与响应(比如透明GZIP压缩)实现基于Headers的缓存策略基本使用同步请求同步的Get请求异步...

weixin_33587731的博客 153

Okhttp3源码

Okhttp3源码 hi,大家好,我是爱吃香蕉的猴子,今天看了很多Okhttp3源码的文章,看云里雾里的,在这我也不贴连接了,整理一篇自己理解的吧。 源码Githup地址 具体的使用过程上面也有介绍,现在步入正题。 从使用切入,再进入源码,最后总结 OkHttpClient client = new OkHttpClient.Builder().build(); Request request = new Request.Builder().

qq_20608169的博客 466

网络---OKhttp缓存

缓存详解来自&lt;https://juejin.im/post/5a6c87c46fb9a01ca560b4d7&gt;你应该了解的 一些web缓存相关的概念.来自&lt;http://www.cnblogs.com/_franky/archive/2011/11/23/2260109.html&gt;HTTP头的Expires与Cache-control来自&lt;http://www.cnb...

qq_24436329的专栏 441

Android最全腾讯面试还不会OkHttp?收藏这一篇就够了!,2024年最新爱奇艺校招面试

针对于上面的问题,我总结出了互联网公司Android程序员面试涉及到的绝大部分面试题及答案,并整理做成了文档,以及系统的进阶学习视频资料。(包括Java在Android开发中应用、APP框架知识体系、高级UI、全方位性能调优,NDK开发,音视频技术,人工智能技术,跨平台技术等技术资料),希望能帮助到你面试前的复习,且找到一个好的工作,也节省大家在网上搜索资料的时间来学习。网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

2401_84544854的博客 393

Okhttp 框架使用和源码分析

Okhttp源码的大致流程,和使用的细节。

NELA的博客 466

OKHttp原理分析

最近生活上出了一些问题,对自己的人生也思考了很多,做安卓开发的程序员确实需要许多努力,可能你稍微有些懈怠就会被别人超过,甚至被行业淘汰,所以大家一定要多努力,但是同时也要注意自己的身体,身体出问题了其他的都成了空谈,好了废话就不多说了这里我们从调用流程上分析一下OKHttp的源码让大家对这个框架有所了解,希望能帮助到你们。 首先看我们的调用流程这里我们做一个简单的调用。 OkHttpCli...

MarsKang的博客 6393
上一篇: Android——AsyncTask源码分析整理
下一篇: WebSocket——OKHttp实现
PdKingLiu
博客等级 码龄9年 89粉丝 92原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值