OkHttp执行流程分析

本人通过源码的解读,只是为了加深对其执行流程的理解,文章中不会对更细致的地方做过多的讲解,只是把握住开源框架的整体脉络。

首先放上一个简单使用的例子:

OkHttpClient client = new OkHttpClient.Builder().build();

Request request = new Request.Builder().url("http://www.baidu.com").build();

Call call = client.newCall(request);

//同步请求
try {
    Response response = call.execute();
    response.close();
} catch (IOException e) {
    e.printStackTrace();
}

//异步请求
call.enqueue(new Callback() {

    @Override
    public void onFailure(Call call, IOException e) {
        //todo failure
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        //todo response
    }
});

如上可以看到OkHttp有两种数据请求方式:同步和异步,其中请求Call是一个接口,实际由RealCall执行。

同步请求方式
public Response execute() throws IOException {
    ......

    Response var2;
    try {
        ...
        Response result = this.getResponseWithInterceptorChain();
        ...
        var2 = result;
    } catch (IOException var7) {
        this.eventListener.callFailed(this, var7);
        throw var7;
    } finally {
        this.client.dispatcher().finished(this);
    }

    return var2;
}

getResponseWithInterceptorChain是一个链式调用的一个方法,该方法是OkHttp的一个精华部分,暂且不讲。
整个同步请求方式还是比较简单的,Call通过execute方法直接请求数据,以及接受数据成功或者失败的回调。

异步请求方式
// RealCall.java
public void enqueue(Callback responseCallback) {
    ......
    this.client.dispatcher().enqueue(new RealCall.AsyncCall(responseCallback));
}

// Dispatcher.java
/**
* 这里有个小细节,异步请求不会是用多少请求就一定会立即会开始多少条请求,而是有个请求数量上限的。
* 只有执行队列的数量<最大请求数,并且正在请求的host数<最大请求host数时才会请求,否则就暂时放在就绪队列里缓存起来
*/
synchronized void enqueue(AsyncCall call) {
    if(this.runningAsyncCalls.size() < this.maxRequests 
        && this.runningCallsForHost(call) < this.maxRequestsPerHost) {
        this.runningAsyncCalls.add(call);
        this.executorService().execute(call);
    } else {
        this.readyAsyncCalls.add(call);
    }
}

final class AsyncCall extends NamedRunnable {
    private final Callback responseCallback;

    ......

    protected void execute() {
        boolean signalledCallback = false;

        try {
            // 1、请求结果
            Response response = RealCall.this.getResponseWithInterceptorChain();
            // 2、结果回调
            if(RealCall.this.retryAndFollowUpInterceptor.isCanceled()) {
                signalledCallback = true;
                this.responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
            } else {
                signalledCallback = true;
                this.responseCallback.onResponse(RealCall.this, response);
            }
        } catch (IOException var6) {
            // 3、失败处理
            if(signalledCallback) {
                Platform.get().log(4, "Callback failure for " + RealCall.this.toLoggableString(), var6);
            } else {
                RealCall.this.eventListener.callFailed(RealCall.this, var6);
                this.responseCallback.onFailure(RealCall.this, var6);
            }
        } finally {
            // 4、结束
            RealCall.this.client.dispatcher().finished(this);
        }

    }
}

public abstract class NamedRunnable implements Runnable {

    public final void run() {
        ...
        this.execute();
        ...
    }

    protected abstract void execute();
}

如上流程可以看出,异步方式就是将RealCall通过包装成AsyncCall,然后在线程池中进行数据请求,然后执行返回数据成功或者失败的处理。

通过以上的分析可以看出,OkHttp无论同步还是异步数据请求,整体的逻辑还是比较简单的,同步就直接在主线程中进行数据请求,异步就是在异步线程池中进行数据请求

无论同步还是异步请求,都有一个非常重要的一个方法:getResponseWithInterceptorChain(),这个方法也是OkHttp的精髓所在。下面具体开始分析该方法的实现。

getResponseWithInterceptorChain方法的实现逻辑分析
Response getResponseWithInterceptorChain() throws IOException {
    List<Interceptor> interceptors = new ArrayList();
    // 用户自定义的拦截器列表
    interceptors.addAll(this.client.interceptors());
    interceptors.add(this.retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(this.client.cookieJar()));
    interceptors.add(new CacheInterceptor(this.client.internalCache()));
    interceptors.add(new ConnectInterceptor(this.client));
    if(!this.forWebSocket) {
        interceptors.addAll(this.client.networkInterceptors());
    }

    interceptors.add(new CallServerInterceptor(this.forWebSocket));
    // 注意第5个参数传递的是0
    Chain chain = new RealInterceptorChain(interceptors, (StreamAllocation)null, (HttpCodec)null, (RealConnection)null, 0, this.originalRequest, this, this.eventListener, this.client.connectTimeoutMillis(), this.client.readTimeoutMillis(), this.client.writeTimeoutMillis());
    return chain.proceed(this.originalRequest);
}

如上可以看出OkHttp除了用户自定义的拦截器之外,主要包括如下几个拦截器RetryAndFollowUpInterceptor、BridgeInterceptor、CacheInterceptor、ConnectInterceptor、NetworkInterceptor和CallServerInterceptor。这几大拦截器共同组成了一个拦截器链,并封装到RealInterceptorChain这个对象当中。
既然是个拦截链,那OkHttp又是如何一条链一条链来进行数据拦截的呢?
下面再看看它的proceed的实现:

public Response proceed(Request request) throws IOException {
    return this.proceed(request, this.streamAllocation, this.httpCodec, this.connection);
}

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException {
    ...
    // 注意第5个参数为index+1
    RealInterceptorChain next = new RealInterceptorChain(this.interceptors, streamAllocation, httpCodec, connection, this.index + 1, request, this.call, this.eventListener, this.connectTimeout, this.readTimeout, this.writeTimeout);
    Interceptor interceptor = (Interceptor)this.interceptors.get(this.index);
    Response response = interceptor.intercept(next);
    ...
    return response;
}

这里大家只看到了其似乎只提取了一条拦截器,如何才能链式调用拦截器?这就是OkHttp设计的一个巧妙之处,正是通过interceptor.intercept(next)来不断的获取下一条拦截器进行数据拦截,然后返回最终的response。
Intercepter是一个接口,这里我拿RetryAndFollowUpInterceptor举例:

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

看到没有,类似这个拦截器一样,每个拦截器都会最终调用realChain.proceed来不断获取下一个拦截器对返回数据进行拦截处理,从而最终得到处理后成功或者失败的数据。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容

  • 用OkHttp很久了,也看了很多人写的源码分析,在这里结合自己的感悟,记录一下对OkHttp源码理解的几点心得。 ...
    蓝灰_q阅读 4,232评论 4 34
  • 那么我今天给大家简单地讲一下Okhttp这款网络框架及其原理。它是如何请求数据,如何响应数据的 有什么优点?它的应...
    卓而不群_0137阅读 310评论 0 1
  • 1、概述 okhttp是一个第三方类库,用于android中请求网络。同时这是一个开源项目,用来替代HttpUrl...
    高丕基阅读 2,531评论 0 15
  • OkHttp源码分析 在现在的Android开发中,请求网络获取数据基本上成了我们的标配。在早期的Android开...
    BlackFlag阅读 323评论 0 5
  • 2017-10-25奥克兰萨维奇纪念公园、维多利亚山。
    朱平阅读 141评论 0 0