OKHttp -- 结构分析

作者: Jcccccccccc | 来源:发表于2017-05-20 11:51 被阅读77次

OKHttp框架图:


OkHttp源码大概流程

这个图片是从拆轮子系列:拆 OkHttp,大神对Okhttp源码分析,他分析得特别好,推荐是看的博文。我只是结合他的总结,然后总结成自己的东西,写一下,希望可以对okhttp更进一步了解。
源码有很多地方值得我们去学习。

一、Builder模式

OKHttpClient,Request,Response等大量的使用这个模式,这些类都需要大量的参数,所以使用Builder模式是很好的设计

  • 1、这个模式可以避免构造方法需要传入大量的参数,相比使用setting的方式设置参数,使用Builder更加清晰。
  • 2、如果有大量的参数,可能会有多个构造方法,有一些默认的参数,这样很容易使用了不对的构造方法。
  • 3、虽然增加了不少代码量,但是客户端的调用非常的清晰
    Builer模式的分析

二、使用队列管理请求,实现高并发

相应的类RealCall、Dispatcher
Dispatcher内部管理了三个队列

三个队列

同时Dispatcher设置了最大请求数64,设置了最大Host5
使用Dispatcher的finished方法控制队列
将线程管理、线程池放在Dispatcher里面进行管理,RealCall、AsyncCall负责执行的逻辑。

同步excute的调用

异步调用A'syncCall最后的调用

不论是同步还是异步,最后都是调用getResponseWithInterceptorChain()

三、责任链模式

OKHttp把责任链模式设计在最核心的地方,每一个请求会有连接、请求、处理返回等等一系列的任务。在OKHttp中已拦截器作为每个责任的任务Interceptor

Interceptor

然后关联到Chain的链条上,在Interceptor的每个intercept中,在执行Chain的proceed方法,知道Chain中没有任务。
getResponseWithInterceptorChain

Interceptors

Interceptors

3.1 RetryAndFollowUpInterceptor

重试重定向拦截器,不断判断返回数据,有问题重试或者重定向
会判断后面拦截器返回的response的值,看是否请求完成,或者需要重定向或者重试
RetryAndFollowUpInterceptor的详细分析

3.2 BridgeInterceptor

Bridges from application code to network code. First it builds a network request from a *user request. Then it proceeds to call the network. Finally it builds a user response *from the network response.

将应用代码转换成网络代码,对用户发送请求的数据进行校验并矫正;同时网络请求返回的数据进行处理,处理为用户希望也是用户能够理解的数据。
BridgeInterceptor源码 主要看intercept方法
chain.proceed调用之前是对请求数据进行转换,调用之后是对请求返回数据进行转换

3.3 CacheInterceptor 缓存拦截器

/** Serves requests from the cache and writes responses to the cache. */

读取缓存和写入更新缓存
缓存机制

3.4 ConnectInterceptor

ConnectInterceptor

看似简单
StreamAllocation 分配流,他实际上是在RetryAndFollowUpInterceptor中创建的,那时候它负责把创建的对象传给chain,如果需要重定向就会重新创建,在这个拦截器中,从其中获取连接,获取编解码器
RealConnection 真是连接,通过streamAllocation寻找可用连接
HttpCodec Http编解码
别人详细的分析
将获取到的内容传给后续的拦截器,获取到返回之后直接返回给前面的拦截器,没有做进一步的处理。

3.5 networkInterceptors

这些是在请求的时候设置的拦截器

3.6 CallServerInterceptor

最后一个拦截器,也是最重要的拦截器,response就是在这个拦截器中通过网络请求获取到的。

@OverridepublicResponse intercept(Chain chain)throwsIOException {
  RealInterceptorChain realChain = (RealInterceptorChain) chain;
  HttpCodec httpCodec = realChain.httpStream();
  StreamAllocation streamAllocation = realChain.streamAllocation();
  RealConnection connection = (RealConnection) realChain.connection();
  Request request = realChain.request();
  longsentRequestMillis = System.currentTimeMillis();
  //写入头部
  httpCodec.writeRequestHeaders(request);
  Response.Builder responseBuilder =null;
  //请求是否有body
  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.
    //头部是否有100-continue,有的话等待response
    if("100-continue".equalsIgnoreCase(request.header("Expect"))) {
      httpCodec.flushRequest();
      responseBuilder = httpCodec.readResponseHeaders(true);
    }

    //没有100-continue 
    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);
      //写入body
      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();
    }
  }

  //完成request写入
  httpCodec.finishRequest();
  if(responseBuilder ==null) {
    //读取头部,并返回response
    responseBuilder = httpCodec.readResponseHeaders(false);
  }
  //创建response
  Response response = responseBuilder
    .request(request)
    .handshake(streamAllocation.connection().handshake())
    .sentRequestAtMillis(sentRequestMillis)
    .receivedResponseAtMillis(System.currentTimeMillis())
    .build();
  
  intcode = response.code();
  //根据类型更新response属性
  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{
    //读取body
    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 newProtocolException(
        "HTTP "+ code +" had non-zero Content-Length: "+     response.body().contentLength());
  }
  return response;
}

继续总结中......

相关文章

网友评论

    本文标题:OKHttp -- 结构分析

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