在 Kotlin 中使用 okhttp 信任 HTTPS 证书时出错
Error when trusting HTTPS certificate using okhttp in Kotlin
我发现了很多与此相关的问题,并且尝试了很多选项。但我无法解决它。我想在使用 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}
请帮助我 this.Also,为什么当 url 是 https 时它显示协议为 http?有没有办法设置它。请帮我解决这个问题。
你的 getUnsafeOkHttpClient()
returns 一个 OkHttpClient.Builder
。
替换
val client = getUnsafeOkHttpClient()
与
val client = getUnsafeOkHttpClient().build()
基本上问题出在请求正文上。将数据 class 映射到请求正文有一些 issues.That 显示 404 错误的原因。无论如何都解决了
我发现了很多与此相关的问题,并且尝试了很多选项。但我无法解决它。我想在使用 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}
请帮助我 this.Also,为什么当 url 是 https 时它显示协议为 http?有没有办法设置它。请帮我解决这个问题。
你的 getUnsafeOkHttpClient()
returns 一个 OkHttpClient.Builder
。
替换
val client = getUnsafeOkHttpClient()
与
val client = getUnsafeOkHttpClient().build()
基本上问题出在请求正文上。将数据 class 映射到请求正文有一些 issues.That 显示 404 错误的原因。无论如何都解决了