[英]Conversion of SSLContext from Java to Kotlin
I was trying to replicate this process of self-signed certificate process (link: https://www.baeldung.com/okhttp-self-signed-cert ) in an android app that is using Kotlin.我试图在使用Z539A3A5859D24FB097BAZ129E7D . The problem is the implementation in the link I've provided is in Java and I can't seem to correctly convert this code to its Kotlin version.
问题是我提供的链接中的实现在 Java 中,我似乎无法将此代码正确转换为其 Kotlin 版本。
sslContext.init(null, new TrustManager[] { TRUST_ALL_CERTS }, new java.security.SecureRandom());
This is how I implemented it in Kotlin:这就是我在 Kotlin 中实现它的方式:
val sslContext: SSLContext = SSLContext.getInstance("SSL")
.init(null, arrayOf(TRUST_ALL_CERTS) as Array<TrustManager>,
java.security.SecureRandom()) as SSLContext
I casted the init to SSLContext because it is in Unit but after doing so, this warning appears:我将 init 转换为 SSLContext 因为它在 Unit 中,但这样做之后,会出现以下警告:
this cast can never succeed
这个演员永远不会成功
What could be an alternative fix for this one?有什么可以解决这个问题的替代方法? Theoretically, it will cause an error once I publish it, and I want to avoid it.
理论上,一旦我发布它就会导致错误,我想避免它。 Please help.
请帮忙。 Thank you
谢谢
Note: I can't test my app on my local machine because the app communicates with a server that will not allow the app to be ran locally.注意:我无法在本地计算机上测试我的应用程序,因为该应用程序与不允许该应用程序在本地运行的服务器通信。
To do it atomically use apply原子地使用 apply
val sslContext: SSLContext = SSLContext.getInstance("SSL").apply {
init(null, arrayOf<TrustManager>(TRUST_ALL_CERTS), java.security.SecureRandom())
}
SSLContext.init()
is returning void
( or Unit
in Kotlin), so you are basically trying to cast Unit
to SSLContext
, which will never successed SSLContext.init()
正在返回void
(或 Kotlin 中的Unit
),因此您基本上是在尝试将Unit
转换为SSLContext
,这永远不会成功
You should seprate statements like this:您应该像这样单独声明:
val sslContext: SSLContext = SSLContext.getInstance("SSL")
sslContext.init(null, arrayOf(TRUST_ALL_CERTS) as Array<TrustManager>,
java.security.SecureRandom())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.