OkHttp 基本使用官网更为详细:点击打开链接
异步流程
OkHttp Dispatcher 源码解析
OKHttp 执行拦截器前
RetryAndFollowUpInterceptor
BridgeInterceptor
CacheInterceptor
基于CallServerInterceptor 文件上传监听
一. 创建OkHttpClient 对象
private void init() {
File externalStorageDirectory =Environment.getExternalStorageDirectory();
File cache=new File(externalStorageDirectory,"cache");
okHttpClient= new OkHttpClient.Builder()
.cache(new Cache(cache,1024*1024))
.build();
}
二.创建Requst 对象并发送同步网络请求public void doSynGet(View view) {
new Thread(new Runnable() {
@Override
public void run() {
Request request = new Request.Builder().url(BASEURL + "login")
.get().build();
try {
Response execute = okHttpClient.newCall(request).execute();
Log.e(TAG, "ru"+execute.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
三.点击发送按钮并能正确的返回正确的数据.那么中间经过了那些步骤?
从上面得知 1.创建OkHttpClient 对象 作用:初始化需要类的实例和管理网络参数.常用的如:
followRedirects:能否重定向 retryOnConnectionFailure:失败能否重连 默认都是true 作用在:RetryAndFollowUpInterceptor 重连和重定向拦截器中
connectTimeout:连接超时 默认10_000;
readTimeout 读取超时 默认10_000;
writeTimeout 写超时 10_000;
类实例 : ConnectionPool 用于管理RealConnection 复用和回收的
Dispatcher :通过三个容器管理RealCall 请求对象和一个ExecutorService 线程调度器去执行异步请求
CookJar:持久化响应头,默认是空实现作用在BrigeInterceptor 桥接拦截器
Cache :用来持久化 响应内容,默认使用自己实现DiskLruCache,作用在CacheInterceptor 缓存拦截器
final List<Interceptor> interceptors; 添加拦截器 final List<Interceptor> networkInterceptors; 网络拦截器
2.创建Requet 对象,作用:存放请求的数据
3.通过OkHttpClient newCall()方法创建一个执行对象
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;
}
然后去execute()执行.
@Override public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true; 设置RealCall 是否已经执行过了
}
captureCallStackTrace();
eventListener.callStart(this);
try {
client.dispatcher().executed(this); 只是添加到同步双端队列容器中
Response result = getResponseWithInterceptorChain();这个才是重点,网络请求和缓存判断都在里面
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
eventListener.callFailed(this, e);
throw e;
} finally {
client.dispatcher().finished(this);只是从同步双端队列容器中删除
}
}
Dispatcher 基本没有做什么事
流程图如下:
ps:不对的地方望指教