整體知識
Carson帶你學(xué)Android:網(wǎng)絡(luò)請求庫Retrofit使用教程(含實例講解) - 簡書
Retrofit一些基礎(chǔ)知識_xuyin1204的博客-CSDN博客
簡單步驟和demo
Retrofit2 實戰(zhàn)(一窿侈、使用詳解篇) - 掘金
進階使用:
1竟坛、類型轉(zhuǎn)換愧杯、rxjava、okhttp彼绷;
2、使用retrofit做為網(wǎng)絡(luò)請求時,解決多個BaseURL切換的問題:添加okhttpclient攔截器融痛,捕獲添加的Headers球凰,然后修改baseURL
Retrofit2詳解_retrofit2 params-CSDN博客
超時-重試-緩存-攔截器
Android-Retrofit-超時-重試-緩存-攔截器 - 簡書
重試兩種方式:
如果不是全局用同一個重試機制狮腿,由于會每次都需要創(chuàng)建一個OkHttpInterceptor,會造成資源浪費呕诉,不建議使用缘厢。
Retrofit實現(xiàn)重試機制(自定義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對象
* 甩挫,而調(diào)用Chain對象的proceed方法(該方法接收一個Request對象)就可發(fā)起一次網(wǎng)絡(luò)請求
* 贴硫,該方法返回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);
}
}
}