简体   繁体   中英

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. 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.

sslContext.init(null, new TrustManager[] { TRUST_ALL_CERTS }, new java.security.SecureRandom());

This is how I implemented it in 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:

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

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

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM