尝试以多种方式解决此问题
我正在使用RxJava和Retrofit来完成所有网络操作。以下是我的代码。
< - HTTP FAILED:java.net.SocketException:Socket closed
Service.kt
@GET("/v1/contact/{id}")
fun getContactDetails(@Path("id") id:String): Flowable<ContactDetailResponse>
AccountRepositoryImpl.kt
override fun contactDetails(contactId:String) {
mContactResponse.loading(true)
remote.getContactDetails(contactId)
.performOnBackOutOnMain(scheduler)
.subscribe({
data -> mContactResponse.success(data)
},{
error -> mContactResponse.failed(error)
})
.addTo(compositeDisposable)
}
Extentions.kt
fun <T> Flowable<T>.performOnBackOutOnMain(scheduler: Scheduler):
Flowable<T> {
return this.subscribeOn(scheduler.io())
.observeOn(scheduler.mainThread())
}
NetworkModule.kt
@Module
class NetworkModule(val key: String, val secret: String) {
@Provides
@Singleton
fun providesRetrofit(jacksonConverterFactory: JacksonConverterFactory,
rxJava2CallAdapterFactory:
RxJava2CallAdapterFactory,
okHttpClient: OkHttpClient,
baseUrl: String): Retrofit {
return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(jacksonConverterFactory)
.addCallAdapterFactory(rxJava2CallAdapterFactory)
.client(okHttpClient)
.build()
}
@Provides
@Singleton
fun providesOkHttpClient(cache: Cache, httpInterceptor:
HttpLoggingInterceptor): OkHttpClient {
val client = OkHttpClient.Builder()
.cache(cache)
.addInterceptor(httpInterceptor)
.retryOnConnectionFailure(true)
.connectTimeout(100, TimeUnit.SECONDS)
.writeTimeout(100, TimeUnit.SECONDS)
.readTimeout(100, TimeUnit.SECONDS)
return client.build()
}
}
答案 0 :(得分:0)
您可以像下面一样创建OkHttp Client,在添加了类似OkhttpClient问题后,我在低端网络中遇到了套接字关闭异常
connectionPool(ConnectionPool(0,1,TimeUnit.NANOSECONDS))
协议(listOf(Protocol.HTTP_1_1))
OkHttpClient.Builder().apply {
.connectionPool(ConnectionPool(0, 1, TimeUnit.NANOSECONDS))
.protocols(listOf(Protocol.HTTP_1_1))
connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
retryOnConnectionFailure(false)
}.build()