第一步:創(chuàng)建OkHttpClient,創(chuàng)建OkHttpClient有兩種方式:
- 使用OkHttpClient()創(chuàng)建(使用默認(rèn)配置)
- 使用OkHttpClient.Builder()構(gòu)建(自定義配置信息)
val okHttpClient = OkHttpClient()
//OR
val okHttpClient = OkHttpClient.Builder().build();
第二步:創(chuàng)建請求Request
使用Request.Builder() 構(gòu)建Request實例
val request: Request = Request.Builder()
.addHeader("token", "abcd")
.get()
.url("https://publicobject.com/helloworld.txt")
.build()
第三步 創(chuàng)建Call對象
var call = client.newCall(request);
第四步 發(fā)起網(wǎng)絡(luò)請求
- 同步請求 execute()
executorService.execute {
try {
val response = okHttpClient.newCall(request).execute() //同步
Log.d("response:", response.body!!.string())
} catch (e: IOException) {
e.printStackTrace()
}
}
- 異步請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分發(fā)器
六余佃、Interceptors攔截器
默認(rèn)的5大攔截器
RetryAndFollowUpInterceptor(重試和重定向攔截器)
第一個接觸到請求,最后接觸到響應(yīng);負(fù)責(zé)判斷是否需要重新發(fā)起整個請求
BridgeInterceptor(橋接攔截器)
補全請求跨算,并對響應(yīng)進(jìn)行額外處理
CacheInterceptor(緩存攔截器)
請求前查詢緩存爆土,獲得響應(yīng)并判斷是否需要緩存
ConnectInterceptor(鏈接攔截器)
與服務(wù)器完成TCP連接 (Socket)
CallServerInterceptor(請求服務(wù)攔截器)
與服務(wù)器通信;封裝請求數(shù)據(jù)與解析響應(yīng)數(shù)據(jù)(如:HTTP報文)
1. 發(fā)送請求確認(rèn)請求地址的問題
第一個攔截器 RetryAndFollowUpInterceptor(重試重定向攔截器)
重試默認(rèn)20次
2. 請求參數(shù)問題
BridgeInterceptor(橋接攔截器)
補全請求參數(shù)
3. 是否有緩存問題
CacheInterceptor(緩存攔截器)
判斷是否使用本地緩存
4. 開始連接
ConnectInterceptor(鏈接攔截器)
與服務(wù)器完成TCP鏈接(Stock)
5. 發(fā)送請求
CallServerInterceptor(請求服務(wù)攔截器)
與服務(wù)器通信;封裝請求數(shù)據(jù)與解析響應(yīng)數(shù)據(jù)