kotlin连接到自签名https服务器 [英] kotlin connect to self-signed https server

查看:196
本文介绍了kotlin连接到自签名https服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下kotlin代码:

I have the following kotlin code:

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连接(仅)?

If I use the above code to connect to a http server, the above code works. However when I try to connect to a https server with a self-signed certificate, it fails. Is there a way to allow https connections on localhost (only), even when the certificates are self-signed ?

推荐答案

以下是从 https://google.com读取的示例使用JSSE,它从字面上信任每个证书,并且不应该被有效率地使用.

Here's an example that reads from https://google.com using JSSE, it trusts literally every certificate and shouldn't be used productively.

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

我为此处提供了一些小库,它们都不是up-至今未发表.但是,它提供了用于设置TLS/SSL套接字的简单DSL,并提供了用于https连接的方法.

I've got a little library for these kinds of things here, which is neither up-to-date nor published. Nevertheless, it provides a simple DSL for setting up TLS/SSL sockets and provides means for https connections.

这篇关于kotlin连接到自签名https服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆