OkHttp

作者: GrapeX | 来源:发表于2020-04-15 15:45 被阅读0次

写在开头

文章地址:https://juejin.im/post/5e1be39b6fb9a02fcd130d1f

本文是对该文章的个人理解总结,仅用于个人复习,有需要看此文章即可。

大纲

  • 使用
  • 解析
  • 责任链模式
  • 总结

使用

最简单的“Get”请求

// 实例客户端
val okHttpClient = OkHttpClient()
// 构建 request 请求参数
val request = Request.Builder().url("http://www.baidu.com").build()
//执行同步请求并返回
val response = okHttpClient.newCall(request).execute()

解析

解析上述三步

1. OkHttpClient()
  1.第一步
  public OkHttpClient() {
    //实例 Builder,构建者模式
    this(new Builder());
  }
  
  2.第二步
  OkHttpClient(Builder builder) {
    this.dispatcher = builder.dispatcher;
    //...其他配置
  }
  
  public static final class Builder {
  Dispatcher dispatcher;
  //...其他配置

  3.第三步
  //new Builder() 会创建一系列默认配置
  public Builder() {
  dispatcher = new Dispatcher();
  //...其他配置
  }
}

总结来说:实例 OkHttp(),就会实例一个 Builder(),它里面会初始化一系列配置。(拦截器,请求超时等)

2. Request.Builder().url("地址").build()

显然也是使用了“Builder”模式

public Builder() {
  this.method = "GET";
  this.headers = new Headers.Builder();
}

默认“GET”方法,这里我们再加了请求的“url”

3. okHttpClient.newCall(request)
  @Override public Call newCall(Request request) {
    return new RealCall(this, request, false /* for web socket */);
  }
  
  RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    //初始化一些配置
    ...
  }

可以看出“okHttpClient”的“newCall”实际是使用了“RealCall”类

4. execute()

最后调用“RealCall”的“execute”请求

@Override public Response execute() throws IOException {
  //同步检查有没有多次执行过
  synchronized (this) {
    if (executed) throw new IllegalStateException("Already Executed");
    executed = true;
  }
  //捕获栈堆跟踪,不需要理会
  captureCallStackTrace();
  try {
    //1. 添加请求到队列
    client.dispatcher().executed(this);
    //2. 重点,可先看最后的责任链的个人理解
    Response result = getResponseWithInterceptorChain();
    if (result == null) throw new IOException("Canceled");
    return result;
  } finally {
    //3. 从队列移除请求
    client.dispatcher().finished(this);
  }
}

//1. 添加请求到队列,从 okHttpClient 拿到 dispatcher( Dispatcher 类)
//   dispatcher 在实例 Buidler 时初始化了
//   runningSyncCall 是 一个双端队列 Deque
synchronized void executed(RealCall call) {
  runningSyncCalls.add(call);
}

//3. 从队列移除请求,没有这个 call 就报错
private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
  int runningCallsCount;
  Runnable idleCallback;
  synchronized (this) {
    if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
    ...
  }
  ...
}

//2. 重点,使用“责任链模式”获取请求结果
Response getResponseWithInterceptorChain() throws IOException {
  //实例 list 存放一些列拦截器
  List<Interceptor> interceptors = new ArrayList<>();
  //将自己在 OkHttpClient 添加的拦截器放入,这里是我没有添加
  interceptors.addAll(client.interceptors());
  //重试并跟踪拦截器,负责失败的重试及重定向
  interceptors.add(retryAndFollowUpInterceptor);
  //负责添加必要的“Header”,接收响应式,移除必要的“Header”
  interceptors.add(new BridgeInterceptor(client.cookieJar()));
  //负责缓存的读取,更新
  interceptors.add(new CacheInterceptor(client.internalCache()));
  //负责和服务器的连接
  interceptors.add(new ConnectInterceptor(client));
  //若不是 webSocket 请求,默认是false
  if (!forWebSocket) {
    // okHttpClient 设置的网络拦截器 ,这里也没有设置
    interceptors.addAll(client.networkInterceptors());
  }
  //负责向服务器发送请求数据,从服务器相应数据
  interceptors.add(new CallServerInterceptor(forWebSocket));
  //责任链实例,RealInterceptorChain 实例
  Interceptor.Chain chain = new RealInterceptorChain(
      interceptors, null, null, null, 0, originalRequest);
  //开始责任链模式调用
  return chain.proceed(originalRequest);
}

5. chain.proceed(originalRequest)
// RealInterceptorChain 的 proceed 方法
@Override public Response proceed(Request request) throws IOException {
  //这里的 streamAllocation, httpCodec, connection 开始是空的
  //但经过责任链的调用,将拦截器的结果返回来后就不为空
  return proceed(request, streamAllocation, httpCodec, connection);
}

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
    RealConnection connection) throws IOException {
  //若 index 大于等于拦截器集合 就报错
  //开始为零,其余的都是其他拦截器责任链模式传来的索引
  //看下面的 RealInterceptorChain next = new RealInterceptorChain
  if (index >= interceptors.size()) throw new AssertionError();
  //标记,一般都是 ++ 后为1, 除非同一个Chain实例被调用了多次 proceed
  calls++;

  //一开始 httpCode,connection为 null
  if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
    throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
        + " must retain the same host and port");
  }
  // httpCodec同上,calls:大于 1 表示自己多次调用了 proceed
  if (this.httpCodec != null && calls > 1) {
    throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
        + " must call proceed() exactly once");
  }
  // 实例下一个拦截器 (参数:index + 1)
  RealInterceptorChain next = new RealInterceptorChain(
      interceptors, streamAllocation, httpCodec, connection, index + 1, request);
  Interceptor interceptor = interceptors.get(index);
  //调用当前拦截器的 interceptor方法,传入下一个拦截器责任链实例
  //该拦截器处理到处理不了的时候,就通过这个责任链的next.processd 回到该方法
  //简单来说:有必要就通过这个实例叫下一个拦截器做事
  Response response = interceptor.intercept(next);

  if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
    throw new IllegalStateException("network interceptor " + interceptor
        + " must call proceed() exactly once");
  }

  if (response == null) {
    throw new NullPointerException("interceptor " + interceptor + " returned null");
  }
  return response;
}

每一个拦截器的 intercept 方法里都有一个 chain.proceed,除了集合添加的最后一个 CallServerInterceptor,因为它之后没有拦截器了。

在 CallServerInterceptor 返回 response 后,其他拦截器再处理完 自己chain.proceed后的方法,最终会返回一个完整的 response

举例看第一个拦截器 “RetryAndFollowUpInterceptor”,这个拦截器就组装了 StreamAllocation streamAllocation参数

  //Chain:这里是下一个拦截器的责任链
  @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    //实例 StreamAllocation
    streamAllocation = new StreamAllocation(
        client.connectionPool(), createAddress(request.url()), callStackTrace);

      ...
      Response response = null;
      boolean releaseConnection = true;
      try {
        //将 streamAllocation 也返回给下一个拦截器处理
        response = ((RealInterceptorChain) chain).proceed(request, streamAllocation, null, null);
        releaseConnection = false;
      } catch (RouteException e) {
      ...
      } 
      ...
  }

责任链模式

我能做的我做,不能的交给下一个人做

比如(这例子是模仿其他作者的举例写的,但实在忘记在哪看的 - -):

主题:公司活动,需要申请 500元 经费。

公司审批经费的额度根据职位不同而不同,部门经理只能批200元,总经理能批1000元。这时我交给了部门经理审批,部门经理看数目后提交给总经理,总经理确定签字。

这就是责任链,能做的就做,不行的就给下一个人处理,自己不再负责,当事人不清楚是谁最终完成了签字。

交给别人后自己不再负责,这也是纯种的责任链模式,但纯种的责任链模式在实际需求中比较少。

实际需求中的责任链,一般都是:我先处理一些东西,发现有些东西处理不了,然后交给其他人继续处理,最后将某些结果返回来再接着处理,OkHttp的责任链模式就是如此。

总结

上面讲了同步请求,异步请求最终也会调用 getResponseWithInterceptorChain() 组装数据,总体流程图如下,

流程图

注:原文里面还有一些拦截器的详解

相关文章

网友评论

      本文标题:OkHttp

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