OkHttp is the most useful Http library in Android develop,it will help us build a http request and send it to server, bring us responses from server, its main work mechanism is Interceptor Chain(bottom of page).
But in the process of http request, OkHttp read OkHttpClient’s configuration list and add it to transact process. There are main member attributes in OkHttpClient.
main member in OkHttpClient
1 | internal var dispatcher: Dispatcher = Dispatcher() |
And their main responsibilities as follows:
dispatcher
Dispatcher will switch thread when we send a request, as we know, it will make ANR(Android Not Responding) if we do network request in UI thread.
protocols
Protocols that OkHttpClient supports, default include Http/1.1 and Http/2.
1 | internal val DEFAULT_PROTOCOLS = immutableListOf(HTTP_2, HTTP_1_1) |
connectionSpecs
Socket’s settings OkHttpClient supports, it default include modern TSL(Https) and clear text(http).
1 | internal val DEFAULT_CONNECTION_SPECS = immutableListOf( |
hostnameVerifier
HostnameVerifier used to verify whether hostname is valid.
certificatePinner
CertificatePinner used to verify certificate, it has default implement, but if we need to self certificate, we can add it by ourself, example as follows:
1 | val client = OkHttpClient.Builder() |
authenticator
Authenticator used to add authenticator header after received service response code 401(authorize fail). Examples as follows
1 | val client = OkHttpClient.Builder().authenticator(object : Authenticator{ |
followRedirects
FollowRedirects can set whether follow url when received response 3XX(redirect).
followSslRedirects
FollowSslRedirects can set whether follow url when received response 3XX(redirect) and current url is a http link, follow url is a https link.
connectTimeout
Set connect socket time limit.
readTimeout
Set read socket data time limit.
writeTimeout
Set write time limit in write data to socket.
other
Can see https’s connection build process at Https build process and OkHttp’s interceptors(bottom of page) chain at Interceptor Chain(bottom of page).