2024-07-08
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
This blog post is parsed with Okhttp 4.6.0hostnameVerfier
As the name suggests, the main function of this method is to identifyhostnname
The legality of Okhttp. We can configure it ourselves when initializing it.hostnameVerfier
:
new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(35, TimeUnit.SECONDS)
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
//注意这里在生产环境中千万不要直接写死true
return true;
}
})
.build();
butThere is a lot of information on the Internetverfiy
Returning true directly is very dangerous.Of course, if vertify returns fasle, it means that the hostname verification fails and the http request cannot succeed. For example, if I initiate an http request with my blog address, the error message is as follows:
{http errorCode=-500, mErrorMsg=Hostname yanchen.blog.csdn.net not verified:
certificate: sha256/tlnf6pbfeu257hnJ9e6j4A1ZWH3vVMzn3Zn3F9kLHdg=
DN: CN=*.blog.csdn.net
subjectAltNames: [*.blog.csdn.net]}
The place where vertify is executed isRealConnectionInside, after execution.
In addition to customhostnameVerfier
In addition, Okhttp provides a default implementation, and now let's analyze the internal principles.
OkHostnameVerifier is built into Okhttp. This method is passedsession.peerCertificates[0] as X509Certificate
Get the certificate object
override fun verify(host: String, session: SSLSession): Boolean {
return try {
verify(host, session.peerCertificates[0] as X509Certificate)
} catch (_: SSLException) {
false
}
}
fun verify(host: String, certificate: X509Certificate): Boolean {
return when {
host.canParseAsIpAddress() -