OkHttp并沒有內置的請求重試機制,但我們可以通過自定義Interceptor來實現請求的重試機制。
以下是一個簡單的示例代碼:
public class RetryInterceptor implements Interceptor {
private int maxRetry;
private int retryCount = 0;
public RetryInterceptor(int maxRetry) {
this.maxRetry = maxRetry;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
while (!response.isSuccessful() && retryCount < maxRetry) {
retryCount++;
response = chain.proceed(request);
}
return response;
}
}
在使用OkHttp時,我們可以創建一個OkHttpClient并添加上述的RetryInterceptor:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new RetryInterceptor(3))
.build();
這樣設置后,每次請求失敗時,RetryInterceptor會嘗試重新發起請求,最多重試3次。這樣就實現了簡單的請求重試機制。