Skip to content

Instantly share code, notes, and snippets.

@vishavgoria
Forked from maiconhellmann/UnsafeOkHttpClient.kt
Created April 27, 2023 13:21
Show Gist options
  • Save vishavgoria/b771d55c9b581fabe924f179411787c1 to your computer and use it in GitHub Desktop.
Save vishavgoria/b771d55c9b581fabe924f179411787c1 to your computer and use it in GitHub Desktop.
UnsafeHttpClient wrote in Kotlin
import okhttp3.OkHttpClient
import java.security.cert.CertificateException
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
class UnsafeOkHttpClient {
companion object {
fun getUnsafeOkHttpClient(): OkHttpClient.Builder {
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
}
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
}
override fun getAcceptedIssuers(): Array<java.security.cert.X509Certificate> {
return arrayOf()
}
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, java.security.SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
val builder = OkHttpClient.Builder()
builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
// builder.hostnameVerifier { _, _ -> true }
builder.hostnameVerifier ( hostnameVerifier = HostnameVerifier{ _, _ -> true })
return builder
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment