kotlin - 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)
}
}```
解决方案
您引用的示例使用 java built-in HttpsUrlConnection
。在 okhttp 中,您需要添加X509TrustManager
、 theHostnameVerifier
和SSLSocketFactory
to OkHttpClient.Builder
(参见https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/ssl-socket-factory / )
推荐阅读
- c - 如何在 Linux 中使用 OpenMax 解码 h264 视频?这段代码正确吗?
- mongodb - 如何使用 MongoDB API 在 Azure CosmosDB 上创建插入触发器
- python - 当我尝试调用我的函数时,为什么会出现 NameError?
- c - STM32 USB CDC 操作
- google-sheets - 使用 Google 表格查询功能将多列视为单个实体
- java - 为什么在休眠时对 ID 使用“long”?
- javascript - 将回调转换为 Promise 以下载多个文件
- webpack - Workbox Service Worker 重复加载或不从缓存中读取?
- elasticsearch - 聚合多个字段而不进行子聚合
- vim - 用许多引号将 shell 输出插入 vim