From 4662731543df10b87f1b2e48e007d3acee769b4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=AD=B1=E5=82=91?= Date: Sun, 11 Sep 2022 23:58:10 +0800 Subject: [PATCH] Fix Https cert issue(#1) --- src/main/kotlin/opencommand/OpenCommandApi.kt | 4 +- src/main/kotlin/utils/UnsafeOkHttpClient.kt | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 src/main/kotlin/utils/UnsafeOkHttpClient.kt diff --git a/src/main/kotlin/opencommand/OpenCommandApi.kt b/src/main/kotlin/opencommand/OpenCommandApi.kt index dcb0643..dc26966 100644 --- a/src/main/kotlin/opencommand/OpenCommandApi.kt +++ b/src/main/kotlin/opencommand/OpenCommandApi.kt @@ -26,13 +26,13 @@ import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream import okhttp3.MediaType.Companion.toMediaType -import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody +import top.jie65535.mirai.utils.UnsafeOkHttpClient @OptIn(ExperimentalSerializationApi::class) object OpenCommandApi { - private val httpClient = OkHttpClient.Builder().build() + private val httpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient().build() private val json = Json { ignoreUnknownKeys = true encodeDefaults = true diff --git a/src/main/kotlin/utils/UnsafeOkHttpClient.kt b/src/main/kotlin/utils/UnsafeOkHttpClient.kt new file mode 100644 index 0000000..555a976 --- /dev/null +++ b/src/main/kotlin/utils/UnsafeOkHttpClient.kt @@ -0,0 +1,44 @@ +package top.jie65535.mirai.utils +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(object : X509TrustManager { + @Throws(CertificateException::class) + override fun checkClientTrusted(chain: Array, authType: String) { + } + + @Throws(CertificateException::class) + override fun checkServerTrusted(chain: Array, authType: String) { + } + + override fun getAcceptedIssuers(): Array { + 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 { _, _ -> true } + + return builder + } catch (e: Exception) { + throw RuntimeException(e) + } + } + } +} \ No newline at end of file