gpt4 book ai didi

kotlin - ktor 客户端 https 请求,带有自签名证书

转载 作者:行者123 更新时间:2023-12-01 18:29:43 24 4
gpt4 key购买 nike

我有一个使用自签名证书运行的 Ktor 服务器应用程序(rest api)。

它在浏览器中工作正常(在警告和确认之后)端口 80 被重定向到 8443。

但是如果我从 Ktor Apache 客户端尝试此操作:

fun main(args: Array<String>) = runBlocking {

val client = HttpClient(Apache) {
install(JsonFeature) {
serializer = GsonSerializer()
}
}

val job = GlobalScope.launch {
try {
//self-signed certificate
val resultWillFail = client.get<String>("https://10.0.0.11:8443/get-my-services")
println("${resultWillFail}")
val resultOk = client.get<String>("https://en.wikipedia.org/wiki/Main_Page") //ok
println("${resultOk}")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}

job.join()
}

我的请求https://10.0.0.11:8443/get-my-services将会失败:

Error: General SSLEngine problem

我也尝试使用curl进行相同的操作:

curl: (77) schannel: next InitializeSecurityContext failed: SEC_E_UNTRUSTED_ROOT (0x80090325) - The certificate chain was issued by an authority that is not trusted.

所以我的问题是:如何在 ktor 客户端(Apache)中使用自签名证书?

谢谢,J

最佳答案

根据 Erik 的回答,这就是我如何让 Ktor Apache 客户端接受自签名证书:

fun main(args: Array<String>) = runBlocking {
val client = HttpClient(Apache) {
install(JsonFeature) {
serializer = GsonSerializer()
}
engine {
customizeClient {
setSSLContext(
SSLContextBuilder
.create()
.loadTrustMaterial(TrustSelfSignedStrategy())
.build()
)
setSSLHostnameVerifier(NoopHostnameVerifier())
}
}
}

val job = GlobalScope.launch {
try {
val sslGetResult = client.get<String>("https://10.0.0.11:8443/get-my-services")
println("${sslGetResult}")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}

job.join()
}

关于kotlin - ktor 客户端 https 请求,带有自签名证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53739245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com