我发现了很多与此相关的问题,并且我尝试了很多选择。但我无法解决它。我想禁用使用 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)
}
我遇到异常:
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/