Skip to content

Instantly share code, notes, and snippets.

@wilinz
Last active April 23, 2024 17:10
Show Gist options
  • Save wilinz/9b661333636f81ab74b1623bb51c5baa to your computer and use it in GitHub Desktop.
Save wilinz/9b661333636f81ab74b1623bb51c5baa to your computer and use it in GitHub Desktop.
OKHttp ignoreCertificate Kotlin

Kotlin Okhttp 忽略证书,OKHttp ignoreCertificate

package com.wilinz.xxx.util
import okhttp3.OkHttpClient
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
private fun OkHttpClient.Builder.ignoreCertificate(): OkHttpClient.Builder {
println("Ignore Ssl Certificate")
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
}
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return arrayOf()
}
}
)
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
this.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
this.hostnameVerifier { hostname, session -> true }
} catch (e: Exception) {
e.printStackTrace()
}
return this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment