Android - 剖析OKHttp(1)- 构建请求

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

源码分析基于 3.14.4

OkHttp是什么东东呢?

OkHttp优点

发起请求大体流程

  1. 创建OkHttpClient,配置拦截器、超时时间等;
  2. 创建Request,配置方法、请求头、请求地址等(Retrofit简化了请求的创建);
  3. 创建Call,用Request构建Call;
  4. call.enqueue加入队列,等待被调度;
  5. 解析结果(Retrofit自定解析以及线程切换)。
    大家注意到了没?在步骤2、5,Retrofit做了封装处理,可以对比看下。

流程图

.png
//创建OkHttpClient
OkHttpClient client = new OkHttpClient.Builder().build();

//OkHttpClient类中
public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
 
  final Dispatcher dispatcher;
  final List<Protocol> protocols;
  final List<ConnectionSpec> connectionSpecs;
  final List<Interceptor> interceptors;
  final List<Interceptor> networkInterceptors;
  final ConnectionPool connectionPool;
  final Dns dns;
  final boolean retryOnConnectionFailure;
  final int connectTimeout;
  final int readTimeout;
  final int writeTimeout;

以上是OkHttpClient几个比较重要属性;

2. 创建Request

跟OkHttpClient类似,也是通过Build模式构建的;

//创建get请求,地址是https://zhuanlan.zhihu.com/api/columns/zhihuadmin
 Request request = new Request.Builder().get().url("https://zhuanlan.zhihu.com/api/columns/zhihuadmin").build();
 
//Request类中
public final class Request {
  final HttpUrl url;
  final String method;
  final Headers headers;
  final @Nullable RequestBody body;
  final Map<Class<?>, Object> tags;

3. 创建Call

Call对象是通过OkHttpClient创建的;

//创建Call
 Call call = client.newCall(request);//最终会调用RealCall.newRealCall

//RealCall类中
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    RealCall call = new RealCall(client, originalRequest, forWebSocket);
    return call;
  }

4.发起请求

//通过enqueue方法发起请求
call.enqueue(new Callback() {//RealCall是Call的实现类,所以调用下面的函数
      @Override
      public void onFailure(Call call, IOException e) {}
     
      @Override
      public void onResponse(Call call, Response response) throws IOException {}
 });
 
//RealCall类中
@Override public void enqueue(Callback responseCallback) {
    synchronized (this) {
        if (executed) throw new IllegalStateException("Already Executed");//1
        executed = true;
      }
    
    client.dispatcher().enqueue(new AsyncCall(responseCallback));//2
  }

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

上一篇下一篇

猜你喜欢

热点阅读