kotlin连接到自签名https服务器

时间:2018-02-28 14:56:36

标签: java android kotlin kotlin-android-extensions kotlin-extension

我有以下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服务器时,它会失败。有没有办法在localhost上允许https连接(仅限),即使证书是自签名的?

1 个答案:

答案 0 :(得分:3)

这是一个使用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设了一个小图书馆,既不是最新的也不是已发表的。然而,它提供了一个简单的DSL来设置TLS / SSL套接字,并为https连接提供了方法。