Okhttp源码阅读理解(一)

Okhttp之Get请求

一.Okhttp基本使用

    异步请求

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

        }
    });


    同步请求

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();

    try {
        Response response = okHttpClient.newCall(request).execute();
    } catch (Exception e) {
        e.printStackTrace();
    }

二.Request
不论是同步请求还是异步请求,都会往OkhttpClient对象的 newCall()方法中传递一个request对象。
通过查看Request 源码能看出,它是包涵了 请求头,url等。那么对它进行处理的就是OkhttpClient 的newCall()方法了。


![ ![reqeustcode3.png](http://upload-images.jianshu.io/upload_images/3087729-f317ed10016acc55.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)](http://upload-images.jianshu.io/upload_images/3087729-1d98aeb6a042dc4d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

三.OkhttpClient.newCall()

newcall1.png

点击进入newCall()函数,发现返回的是一个RealCall(),进入RealCall()

RealCall 是 Call 的实现类, 所以会有execute()方法和enqueue()方法;

realcall1.png

在RealCall()方法中,主要初始化监听等一些变量。
最为关键的是该类的execute()和enqueue();

四 .RealCall 中的excuse();

realcall2.png

看到这句
Response result = getResponseWithInterceptorChain();
说明得到的结果是由getResponseWithInterceptorChain()得到的,进入这个方法。

newcall4.png

看到里面各种Iterceptor, 有连接相关的拦截器,缓存相关的拦截器等。先不管拦截器,看

Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);

其中originalRequest 是一个Request对象

newcall5.png

由此可知,chain.proceed()返回一个Response结果对象
而chain对象是由new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest)对象而来的, 点进RealInterceptorChain类一看究竟。
查看RealInterceptorChain类下的proceed()这个方法

newcall6.png

Response response = interceptor.intercept(next);
最终我们还是要看各种Interceptor, 那么跟网络连接相关的就属ConnectInterceptor,进入ConnectInterceptor类,并找到intercept()方法

newcall7.png

发现有个RealConnection类,进入RealConnection发现这么一段

newcall8.png

ok真正的网络连接找到了。

进入connectTunnel();

newcall9.png

再进入createTunnel()

newcall10.png

最后总算找到了 Response。

五.RealCall中的enqueue();


realcall3.png

发现

 client.dispatcher().enqueue(newAsyncCall(responseCallback));

点击进入Dispatcher类

dispathcer.png

有个线程池,里面包裹三个集合别代表了
1.正在准备的异步请求
2.已经结束的请求
3.正在准备的同步请求

继续看


enqueue.png

这其实是执行了一个线程池
在进入AsyncCall类

asynccall.png

发现了和同步请求一样的字段,那么可以得出的结论是,其实异步比起同步请求来,就多出了一个线程池。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容