okhttp之RealCall.execute()流程介绍

转载请以链接形式标明出处:
本文出自:103style的博客


base on 3.12.0


目录

  • 前言
  • OkHttpClient.newCall(Request)
  • RealCall.execute()
  • RealInterceptorChain.proceed(request)
  • 小结

前言

前面我们对 OkHttpClientRequest 做了相关的介绍。

此时我们已经构建了 http客户端http请求,接下来就好通过 http客户端 来执行http请求。即先通过OkHttpClient.newCall(Request)构建RealCall,然后通过 RealCall.execute() 来执行请求。


OkHttpClient.newCall(Request)

通过下面的源码我们知道 OkHttpClientnewCall 方法即通过 RealCall.newRealCall()构建了一个RealCall实例,将 OkHttpClientRequest 赋值给实例的成员变量. 以及初始化了拦截器 RetryAndFollowUpInterceptor.

//OkHttpClient
public Call newCall(Request request) {
    return RealCall.newRealCall(this, request, false );
}
//RealCall
private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    this.client = client;
    this.originalRequest = originalRequest;
    this.forWebSocket = forWebSocket;
    this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client, forWebSocket);
    this.timeout = new AsyncTimeout() {
        @Override protected void timedOut() {
            cancel();
        }
    };
    this.timeout.timeout(client.callTimeoutMillis(), MILLISECONDS);
}
static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
    // Safely publish the Call instance to the EventListener.
    RealCall call = new RealCall(client, originalRequest, forWebSocket);
    call.eventListener = client.eventListenerFactory().create(call);
    return call;
}

RealCall.execute()

public Response execute() throws IOException {
    ...
    try {
        client.dispatcher().executed(this);
        Response result = getResponseWithInterceptorChain();
        ...
    } catch (IOException e) {
        ...
    } finally {
        client.dispatcher().finished(this);
    }
}

通过上面的代码我们知道是通过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);
}

getResponseWithInterceptorChain中依次添加了以下的拦截器,后面会具体介绍:

  • client.interceptors():我们通过OkhttpClient添加的自定义拦截器
  • retryAndFollowUpInterceptor:重试及重定向拦截器
  • BridgeInterceptor:桥接拦截器
  • CacheInterceptor:缓存拦截器
  • ConnectInterceptor:连接拦截器
  • client.networkInterceptors():网络请求的拦截器
  • CallServerInterceptor:读写拦截器

然后将 request请求interceptors这个拦截器集合构建了一个 RealInterceptorChain.
然后通过RealInterceptorChain.proceed(originalRequest);返回请求结果。


RealInterceptorChain.proceed(request)

public Response proceed(...) throws IOException {
    if (index >= interceptors.size()) throw new AssertionError();
    calls++;
    ...
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
            connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
            writeTimeout);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    ...
    return response;
}

我们可以看到这里通过interceptor.intercept(next);获取的请求结果。
我们先以RetryAndFollowUpInterceptor来介绍下。

public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    ...
    response = realChain.proceed(request, streamAllocation, null, null);
    ...
}

看到上面代码中的realChain.proceed(...);方法,是不是又回到了上面的RealInterceptorChain.proceed(request).

所以由此可知RealInterceptorChain.proceed(request)会 “依次” 去调用拦截器列表每个interceptors中的interceptor.intercept(next),如下图:
RealCall.execute()

拦截器具体做了什么操作呢?请听下回分解。见 okhttp之五个拦截器的介绍


小结

通过上面的介绍,我们知道了:

  • OkHttpClient.newCall(Request)构建了一个 RealCall 实例。
  • RealCall.execute()通过添加一系列拦截器,然后依次执行拦截器的intercept(chain)方法,然后把响应结果再一层一层回传到给 RealCall

以上

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
E/AndroidRuntime: FATAL EXCEPTION: Thread-18 Process: com.example.read, PID: 22568 java.lang.RuntimeException: java.net.UnknownServiceException: CLEARTEXT communication to 192.168.210.113 not permitted by network security policy at com.example.read.upload_serverActivity$1.run(upload_serverActivity.java:111) at java.lang.Thread.run(Thread.java:920) Caused by: java.net.UnknownServiceException: CLEARTEXT communication to 192.168.210.113 not permitted by network security policy at okhttp3.internal.connection.RealRoutePlanner.planConnectToRoute$okhttp(RealRoutePlanner.kt:195) at okhttp3.internal.connection.RealRoutePlanner.planConnect(RealRoutePlanner.kt:152) at okhttp3.internal.connection.RealRoutePlanner.plan(RealRoutePlanner.kt:67) at okhttp3.internal.connection.FastFallbackExchangeFinder.launchTcpConnect(FastFallbackExchangeFinder.kt:118) at okhttp3.internal.connection.FastFallbackExchangeFinder.find(FastFallbackExchangeFinder.kt:62) at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:267) at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109) at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109) at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:84) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109) at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:65) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109) at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:205) at okhttp3.internal.connection.RealCall.execute(RealCall.kt:158) at com.example.read.upload_serverActivity$1.run(upload_serverActivity.java:106) at java.lang.Thread.run(Thread.java:920) 怎么解决
05-29

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值