首页 > 解决方案 > Kotlin Retrofit 忽略 https 证书

问题描述

Kotlin Retrofit 忽略 https 证书。

我试过这个Android 忽略自签名证书并转换为 Kotlin。它不工作。

我如何忽略 https (SSL) 证书。

我的 OkHttp 是


import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object OwnRetrofitClient {

    private val authInterceptor = Interceptor { chain ->
        val newUrl = chain.request().url
            .newBuilder()
            .build()

        val newRequest = chain.request()
            .newBuilder()
            .addHeader("Authorization", "bearer " + AppPreferences.token)
            .url(newUrl)
            .build()

        chain.proceed(newRequest)
    }

    private val client =
        OkHttpClient().newBuilder()
            .addInterceptor(authInterceptor)
            .connectTimeout(120, TimeUnit.SECONDS)
            .readTimeout(120, TimeUnit.SECONDS)
            .writeTimeout(90, TimeUnit.SECONDS)
            .build()

    private fun retrofit(baseUrl: String = "https:some.com/api") =
        Retrofit.Builder()
            .client(client)
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .build()

    fun apiService(): ApiService {
        return retrofit().create(ApiService::class.java)
    }
}```


标签: kotlinhttpsretrofitokhttp

解决方案


您引用的示例使用 java built-in HttpsUrlConnection。在 okhttp 中,您需要添加X509TrustManager、 theHostnameVerifierSSLSocketFactoryto OkHttpClient.Builder(参见https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/ssl-socket-factory / )


推荐阅读