OkHttpClient okHttpClient = new OkHttpClient();
Request request=new Request.Builder()
.url("http://www.baidu.com/")
.build();
Call call= okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
okHttp是一个高性能的http库,支持ip切换、url重试、线程管理、缓存管理、连接复用等
支持HTTPS/HTTP2/WebSocket(服务器可主动推送消息)
内部维护任务队列线程池,友好支持并发访问
内部维护连接池,支持多路复用,减少连接创建开销
提供拦截器链,实现request和response的分层处理
Okio提供超时机制
Socket创建支持最佳路由
官网对拦截器的解释是:拦截器是OkHttp中提供的一种强大机制,它可以实现网络监听、请求以及响应重写、请求失败重试等功能。
1 RetryAndFollowUpInterceptor
检验返回的 Response ,如果出现异常情况,则进行重连操作。
2 BridgeInterceptor 侨接拦截器
设置内容长度,内容编码
设置gzip压缩,并在接收到内容后进行解压。省去了应用层处理数据解压的麻烦
添加cookie
设置其他报头,如User-Agent,Host,Keep-alive等,其中Keep-Alive是实现多路复用的必要步骤
3 CacheInterceptor 缓存拦截器
功能: 实现缓存功能的拦截器
当网络请求有符合要求的Cache时直接返回Cache
当服务器返回内容有改变时更新当前cache
如果当前cache失效,删除
4 ConnectInterceptor
打开一个面向指定服务器的连接,并且执行下一个拦截器
5 CallServerInterceptor
这是 Okhttp 库中拦截器链的最后一个拦截器,也是这个拦截器区具体发起请求和获取响应。
Response getResponseWithInterceptorChain() throws IOException { // Build a full stack of interceptors.
List 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()); //标记1
return chain.proceed(originalRequest);
}
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
...
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index); //标记1:取出index位置的拦截器
Response response = interceptor.intercept(next); //标记2
... return response;
}
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
...
RealInterceptorChain realChain = (RealInterceptorChain) chain;
...
response = realChain.proceed(request, streamAllocation, null, null);
...
}
创建一系列拦截器,并将其放入一个拦截器list集合中。
创建一个拦截器链RealInterceptorChain,并执行拦截器链的proceed方法,这个proceed方法的核心是继续创建下一个拦截器链。