整体知识
Carson带你学Android:网络请求库Retrofit使用教程(含实例讲解) - 简书
Retrofit一些基础知识_xuyin1204的博客-CSDN博客
简单步骤和demo
进阶使用:
1、类型转换、rxjava、okhttp;
2、使用retrofit做为网络请求时,解决多个BaseURL切换的问题:添加okhttpclient拦截器,捕获添加的Headers,然后修改baseURL
Retrofit2详解_retrofit2 params-CSDN博客
超时-重试-缓存-拦截器
Android-Retrofit-超时-重试-缓存-拦截器 - 简书
重试两种方式:
如果不是全局用同一个重试机制,由于会每次都需要创建一个OkHttpInterceptor,会造成资源浪费,不建议使用。
Retrofit实现重试机制(自定义Interceptor或封装callback)_retrofit 重试-CSDN博客
做个完善
public class OkHttpRetryInterceptor implements Interceptor {
private List<Long> retryIntervalList = new ArrayList<>();
public OkHttpRetryInterceptor(List<Long> retryIntervalList) {
if (retryIntervalList != null && !retryIntervalList.isEmpty()) {
this.retryIntervalList = retryIntervalList;
return;
}
//默认1.5秒重试一次
retryIntervalList.add(1500L);
}
/**
* 该方法提供了一个Chain类型的对象,Chain对象中可以获取到Request对象
* ,而调用Chain对象的proceed方法(该方法接收一个Request对象)就可发起一次网络请求
* ,该方法返回Response对象。
*
* @param chain
* @return
* @throws IOException
*/
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = doRequest(chain, request);
if (response != null && response.isSuccessful()) {
return response;
}
for (int i = 0; i < retryIntervalList.size(); i++) {
Long retryInterval = retryIntervalList.get(i);
if (retryInterval == null) {
continue;
}
if (i == 0 || ((response == null) || !response.isSuccessful())) {
try {
Thread.sleep(retryInterval);
} catch (Exception e) {
e.printStackTrace();
}
response = doRequest(chain, request);
}
}
return response;
}
private Response doRequest(Chain chain, Request request) {
try {
return chain.proceed(request);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static class Builder {
private List<Long> retryIntervalList = new ArrayList<>();
public Builder buildRetryInterval(List<Long> retryIntervalList) {
this.retryIntervalList = retryIntervalList;
return this;
}
public OkHttpRetryInterceptor build() {
return new OkHttpRetryInterceptor(retryIntervalList);
}
}
}