Technology Sharing

Okhttp hostnameVerifier detailed explanation

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Method Introduction

This blog post is parsed with Okhttp 4.6.0hostnameVerfierAs the name suggests, the main function of this method is to identifyhostnnameThe 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 InternetverfiyReturning 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:
insert image description here

{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.
insert image description here

In addition to customhostnameVerfierIn addition, Okhttp provides a default implementation, and now let's analyze the internal principles.

Core Principles

OkHostnameVerifier is built into Okhttp. This method is passedsession.peerCertificates[0] as X509CertificateGet 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() -