简述OkHttp 流程

2023-07-24  本文已影响0人  简单快乐6

第一步:创建OkHttpClient,创建OkHttpClient有两种方式:

  1. 使用OkHttpClient()创建(使用默认配置)
  2. 使用OkHttpClient.Builder()构建(自定义配置信息)
val okHttpClient = OkHttpClient()
//OR
 val okHttpClient = OkHttpClient.Builder().build();

第二步:创建请求Request

使用Request.Builder() 构建Request实例

val request: Request = Request.Builder()
        .addHeader("token", "abcd")
        .get()
        .url("https://publicobject.com/helloworld.txt")
        .build()

第三步 创建Call对象

var call = client.newCall(request);

第四步 发起网络请求

  1. 同步请求 execute()
executorService.execute {
    try {
        val response = okHttpClient.newCall(request).execute() //同步
        Log.d("response:", response.body!!.string())
    } catch (e: IOException) {
        e.printStackTrace()
    }
}
  1. 异步请enqueue()
okHttpClient.newCall(request).enqueue(object : Callback {
    //异步
    override fun onFailure(call: Call, e: IOException) {
        e.printStackTrace()
    }

    @Throws(IOException::class)
    override fun onResponse(call: Call, response: Response) {
        Log.d("response:", response.body!!.string())
    }
})

五、Dispatcher分发器

六、Interceptors拦截器

默认的5大拦截器
RetryAndFollowUpInterceptor(重试和重定向拦截器)
第一个接触到请求,最后接触到响应;负责判断是否需要重新发起整个请求
BridgeInterceptor(桥接拦截器)
补全请求,并对响应进行额外处理
CacheInterceptor(缓存拦截器)
请求前查询缓存,获得响应并判断是否需要缓存
ConnectInterceptor(链接拦截器)
与服务器完成TCP连接 (Socket)
CallServerInterceptor(请求服务拦截器)
与服务器通信;封装请求数据与解析响应数据(如:HTTP报文)

1. 发送请求确认请求地址的问题
第一个拦截器 RetryAndFollowUpInterceptor(重试重定向拦截器)
重试默认20次
2. 请求参数问题
BridgeInterceptor(桥接拦截器)
补全请求参数
3. 是否有缓存问题
CacheInterceptor(缓存拦截器)
判断是否使用本地缓存
4. 开始连接
ConnectInterceptor(链接拦截器)
与服务器完成TCP链接(Stock)
5. 发送请求
CallServerInterceptor(请求服务拦截器)
与服务器通信;封装请求数据与解析响应数据
上一篇下一篇

猜你喜欢

热点阅读