Android11更新后的UnknownHostException
问题:一旦返回 UnknownHostException,用户将继续收到相同的错误,除非重新安装应用程序或重新启动设备。
在操作系统为 Android 11 的用户中,只有少数用户遇到问题。
最大的问题是,当发生错误时,每次请求都会不断返回相同的错误。
据用户称,重新安装应用程序或重新启动设备将再次起作用。
似乎 99% 是三星设备的用户。有时也有 Google Pixel 手机。
Http 和 Https 都给出相同的错误。
Wifi、5G 和 LTE 都会出现相同的错误。
请求方法是使用POST,我不知道GET是否也是如此,我不使用GET。
此外,线程是背景或前景,或两者兼而有之。
在这个我的代码
摇篮:
android {
minSdkVersion 21
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
/* RETROFIT */
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'
/* OKHTTP */
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:4.9.0'
/* RXJAVA RXANDROID */
implementation 'io.reactivex.rxjava3:rxjava:3.0.11'
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
}
创建请求:
interface ApiService {
@POST("get-data")
fun getData(@Body parameter : CustomParameter): Single<Response<CustomObject>>
companion object {
private val rxJava3CallAdapterFactory: RxJava3CallAdapterFactory
get() = RxJava3CallAdapterFactory.createWithScheduler(Schedulers.io())
private fun okHttpClient(): OkHttpClient {
val okHttpClientBuilder = okHttpClientBuilder()
okHttpClientBuilder.addNetworkInterceptor { chain ->
val request = chain.request()
val response = chain.proceed(request)
if (response.code >= 400) {
handleNetworkError()
}
response
}
okHttpClientBuilder.addInterceptor { chain ->
val request = chain.request()
chain.proceed(request)
}
return okHttpClientBuilder.build()
}
fun createApiService(context: Context): ApiService {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(rxJava3CallAdapterFactory)
.client(okHttpClient())
.build()
return retrofit.create(ApiService::class.java)
}
}
}
呼叫请求(活动中):
ApiService.createMainWeatherApiService().getData(CustomParameter())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ res ->
handleSuccess()
},
{ error ->
// UnknownHostException!!!!
handleFail()
}
).apply { compositeDisposable.add(this) }
我在 okhttp 上创建了一个问题:https : //github.com/square/okhttp/issues/6591