gpt4 book ai didi

android - 在 Kotlin 中使用 okhttp 信任 HTTPS 证书时出错

转载 作者:行者123 更新时间:2023-12-02 12:47:19 49 4
gpt4 key购买 nike

我发现了很多相关的问题,我尝试了很多选择。但我无法解决它。我想在使用 okhttp 进行 API 调用时禁用认证检查.

下面是我尝试过的代码

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 }

return builder
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
}

在提出请求 :
 fun getAppList(requestbody: AppListRequestBody, baseUrl: String): AppListResponse {

val gson = GsonBuilder().create()
val appListRequestInfo: String = gson.toJson(requestbody)
val JSON = MediaType.parse("application/json")
val appListBody: RequestBody = RequestBody.create(JSON, appListRequestInfo)
val client =getUnsafeOkHttpClient().build

var appListRequest: Request = Request.Builder()
.url("$baseUrl/apps/mobile")
.post(appListBody)
.addHeader("Content-Type", "application/json")
.build()
val appResponse: Response = client.newCall(appListRequest).execute() //Getting syntax error
if (!appResponse.isSuccessful) {
Log.e("Exception =",appResponse.message())
throw Exception(appResponse.code().toString())
}
Log.d("App list res",appResponse.body().toString())
return Gson().fromJson(appResponse.body()!!.string(), AppListResponse::class.java)
}

我遇到了一个异常(exception):
Response{protocol=http/1.1, code=404, message=Not Found}

请帮我解决这个问题。另外,当 url 是 https 时,为什么它显示协议(protocol)为 http?有什么办法可以设置。请帮我解决这个问题。

最佳答案

您的 getUnsafeOkHttpClient()返回 OkHttpClient.Builder .

代替

    val client = getUnsafeOkHttpClient()


    val client = getUnsafeOkHttpClient().build()

关于android - 在 Kotlin 中使用 okhttp 信任 HTTPS 证书时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54977069/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com