添加依赖
1 | implementation 'com.squareup.okhttp3:okhttp:3.10.0' |
使用方法
1 | OkHttpClient client = new OkHttpClient(); |
发起请求
加入各种拦截器 用到责任链的思想
1.客户端自定义的拦截器 可以做一些日志的打印
2.重试与重定向拦截器 哪些请求需要重试 重试策略 哪些请求需要重定向之类
3.桥接拦截器 将客户端的request对象转化为一个服务器认识的请求 添加头信息 cookie等信息
4.缓存拦截器 判断哪些请求是不需要走服务器 可以直接走缓存的处理
5.连接拦截器 建立 获取一个有效的服务器连接
6.客户端自定义的拦截器 可以做一些向服务器传递之前的统一操作 添加公共参数 url签名校验 包体加密等
7.调用服务拦截器 真正的与服务器交互的拦截器
1 |
|
具体执行每个拦截器
1 | public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, |
RetryAndFollowUpInterceptor 重试与重定向拦截器
1 |
|
BridgeInterceptor 桥梁拦截器(客户端代码和网络代码的桥接)
1 |
|
CacheInterceptor 缓存拦截器
1 |
|
ConnectInterceptor 建立Socket连接拦截器
1 |
|
CallServerInterceptor 真正的与服务器交换数据的拦截器
1 | public Response intercept(Chain chain) throws IOException { |