java.io.IOException: Hostname was not verified

后端 未结 10 635
逝去的感伤
逝去的感伤 2020-11-28 06:27

I am trying to connect to a URL from a my Android app in Andorid Version 4.1.1, and I get the error indicated in the Title of my question, but when I tried to connect the sa

10条回答
  •  时光说笑
    2020-11-28 07:20

    In Kotlin:

    fun HttpsURLConnection.trustCert() {
                try {
                    //Accepts every hostname
                    this.hostnameVerifier = HostnameVerifier { hostname, _ ->
                        println(hostname) //To be hardcoded/as needed
                        true
                    }
                    val trustMgr:Array = arrayOf(object : X509TrustManager {
                        override fun checkClientTrusted(certs: Array?, authType: String?) {}
                        override fun checkServerTrusted(certs: Array?, authType: String?) {}
                        override fun getAcceptedIssuers(): Array? = null
                    })
                    this.sslSocketFactory = SSLContext.getInstance("TLS").also {
                        it.init(null, trustMgr, SecureRandom())
                    }.socketFactory
                } catch (e: Exception) {
                    prinntln("SSL self-signed certificate processing error due to ${e.message}")
                }
            }
    

    Usage:

    val conn = URL(Uri.Builder().also { 
        it.scheme("https")
        it.encodedAuthority("$serverIp:$serverPort")
    }.build().toString()).openConnection() as HttpsURLConnection
    conn.trustCert()
    val respCode = conn.responseCode
    if(respCode == 200) {
        //do something (eg: read inputStream)
    }
    

提交回复
热议问题