kotlin 连接到自签名 https 服务器

kotlin connect to self-signed https server

我有以下 kotlin 代码:

val urlPath = "https://10.0.2.2:8080"
var data: String
try {
    data = URL(urlPath).readText()
} catch (e: Exception) {
    Log.e("doInBackground", "Exception caught: ${e.localizedMessage}")
    error = when (e) {
        is MalformedURLException -> "Invalid URL"
        is IOException -> "Network Error"
        else -> {
            "Network error: ${e.localizedMessage}"
        }
    }
}

如果我使用上面的代码连接到 http 服务器,上面的代码可以工作。但是,当我尝试使用自签名证书连接到 https 服务器时,它失败了。有没有办法允许本地主机上的 https 连接(仅),即使证书是自签名的?

这是一个使用 JSSE 从 https://google.com 中读取的示例,它几乎信任每个证书,不应有效使用。

fun main(args: Array<String>) {
    val urlPath = "https://google.com"
    try {
        (URL(urlPath).openConnection() as HttpsURLConnection).apply {
            sslSocketFactory = createSocketFactory(listOf("TLSv1.2"))
            hostnameVerifier = HostnameVerifier { _, _ -> true }
            readTimeout = 5_000
        }.inputStream.use {
            it.copyTo(System.out)
        }
    } catch (e: Exception) {
        TODO()
    }
}


private fun createSocketFactory(protocols: List<String>) =
    SSLContext.getInstance(protocols[0]).apply {
        val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
            override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
            override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
            override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
        })
        init(null, trustAllCerts, SecureRandom())
    }.socketFactory

我有一个关于这些东西的小图书馆 here,它既没有 up-to-date 也没有出版。然而,它提供了一个简单的 DSL 来设置 TLS/SSL 套接字并提供 https 连接的方法。