- 连接池减少了请求延迟(如果 HTTP/2 不可用)。
- 透明 GZIP 缩小下载大小。
- 响应缓存完全避免网络重复请求。
本博客引用的okhttp版本:com.squareup.okhttp3:okhttp:4.9.0
GET请求
下面代码将请求博主GitHub账户公开信息,并且打印。🙆♀️
simpleGetUse(“https://api.github.com/users/zhangnangua”)
fun simpleGetUse(url: String) {
//创建OkHttpClient
val okHttpClient = OkHttpClient()
//构建request
val requestBuilder = Request.Builder().url(url)
//调用newCall 返回call对象,此后调用enqueue进行异步请求
okHttpClient.newCall(requestBuilder.build()).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
log(“go failure ${e.message}”)
}
override fun onResponse(call: Call, response: Response) {
val msg = if (response.isSuccessful) {
simpleDealData(response)
} else {
“failure ${response.message}”
}
log(msg)
}
})
}
//该函数用于简单处理返回的信息,这里放一次,下面就不放了。
private fun simpleDealData(response: Response): String = StringBuilder().apply {
append(“\n\t”)
append(“header”)
append(“\n\t”)
append(response.he