Okhttp通过自定义,可以通过拦截器的方式
使用Rxjava 实现
/**
* @params maxRetry 最大次数
*/
private class InterceptorRetryOkhttp(private val maxRetry: Long) : Interceptor, KoinComponent {
override fun intercept(chain: Interceptor.Chain): Response {
return try {
Single.create{ it.onSuccess(chain.proceed(chain.request())) }.retry(maxRetry-1).blockingGet()
} catch (e: Exception) {
chain.proceed(chain.request())
}
}
}
使用递归实现
private class InterceptorRetryOkhttp(private val maxRetry: Long) : Interceptor, KoinComponent {
override fun intercept(chain: Interceptor.Chain): Response {
return retry(chain=chain,retryCount = 0)
}
private fun retry(chain: Interceptor.Chain,retryCount:Long):Response{
val request =chain.request()
var response:Response? =null
try {
response =chain.proceed(request)
}catch (e:Exception){
if (retryCount<maxRetry){
retry(chain, retryCount+1)
}
}
return response?: chain.proceed(request)
}
}
```kotlin
OkHttpClient.Builder().addInterceptor(InterceptorRetryOkhttp(maxRetry=3))