当我使用嘲笑httpserver测试http请求时,出现上述错误,以下代码是我创建服务的方式。
iNEXT
这是我的测试代码。
fun <T> getService(clazz: Class<T>): T {
val client = OkHttpClient.Builder().addInterceptor(HeaderInterceptor()).addInterceptor(HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE })
.build()
return Retrofit.Builder()
.baseUrl(mockWebServer.url(""))
.client(client)
.addConverterFactory(GsonConverterFactory.create(GSON))
.build()
.create(clazz)
}
除运行我的单元测试代码外,其他所有内容均可在我的应用上正常运行。 有一个类似的problem,但与该问题相比,我的问题有所不同。 我曾尝试过很多解决类似问题的方法,但没有用。
PS:如果测试代码在Junit4Test上运行,而不在AndroidJunit4Test上运行,则它将正常运行。但是现在我需要进行集成测试。因此,这部分代码需要在AndroidJunit4Test上执行
答案 0 :(得分:3)
解决方案1)
在AndroidManifest.xml中的<application
标签中添加以下属性:
android:usesCleartextTraffic="true"
解决方案2)
将android:networkSecurityConfig="@xml/network_security_config"
添加到<application
中的app/src/main/AndroidManifest.xml
标记中:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:networkSecurityConfig="@xml/network_security_config"
android:theme="@style/AppTheme">
在network_security_config.xml
中有一个对应的app/src/main/res/xml/
:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
答案 1 :(得分:1)
就我而言,我将此添加到 android 清单文件中:
seat_count
答案 2 :(得分:0)
问题终于根据@Yuri Schimke提示解决了。
第一步:mockwebserver使用https
val mockWebServer = MockWebServer().apply {
val localhost: String = InetAddress.getByName("localhost").canonicalHostName
val localhostCertificate: HeldCertificate = HeldCertificate.Builder().addSubjectAlternativeName(localhost)
.build()
val serverCertificates = HandshakeCertificates.Builder()
.heldCertificate(localhostCertificate)
.build()
useHttps(serverCertificates.sslSocketFactory(), false)
}
第二步:使用不安全的okhttp客户端
private fun getUnsafeOkHttpClient(): OkHttpClient.Builder? {
return try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf<TrustManager>(
object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(chain: Array<X509Certificate?>?, authType: String?) {
}
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array<X509Certificate?>?, authType: String?) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return arrayOf()
}
}
)
// Install the all-trusting trust manager
val sslContext: SSLContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory: SSLSocketFactory = sslContext.getSocketFactory()
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
builder.hostnameVerifier(HostnameVerifier { hostname, session -> true })
builder
} catch (e: Exception) {
throw RuntimeException(e)
}
}
完成此操作后,您可以按照以下代码创建自己的服务。
fun <T> getService(clazz: Class<T>): T {
val client =getUnsafeOkHttpClient()!!.addInterceptor(HeaderInterceptor())
.addInterceptor(HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE })
.build()
return Retrofit.Builder()
.baseUrl(mockWebServer.url(""))
.client(client)
.addConverterFactory(GsonConverterFactory.create(GSON))
.build()
.create(clazz)
}
如果您在AndroidJunit4上具有okhttp单元测试,希望这会有所帮助