整體知識(shí)
Carson帶你學(xué)Android:網(wǎng)絡(luò)請(qǐng)求庫(kù)Retrofit使用教程(含實(shí)例講解) - 簡(jiǎn)書
Retrofit一些基礎(chǔ)知識(shí)_xuyin1204的博客-CSDN博客
簡(jiǎn)單步驟和demo
Retrofit2 實(shí)戰(zhàn)(一、使用詳解篇) - 掘金
進(jìn)階使用:
1、類型轉(zhuǎn)換、rxjava、okhttp;
2、使用retrofit做為網(wǎng)絡(luò)請(qǐng)求時(shí),解決多個(gè)BaseURL切換的問(wèn)題:添加okhttpclient攔截器,捕獲添加的Headers,然后修改baseURL
Retrofit2詳解_retrofit2 params-CSDN博客
超時(shí)-重試-緩存-攔截器
Android-Retrofit-超時(shí)-重試-緩存-攔截器 - 簡(jiǎn)書
重試兩種方式:
如果不是全局用同一個(gè)重試機(jī)制,由于會(huì)每次都需要?jiǎng)?chuàng)建一個(gè)OkHttpInterceptor,會(huì)造成資源浪費(fèi),不建議使用。
Retrofit實(shí)現(xiàn)重試機(jī)制(自定義Interceptor或封裝callback)_retrofit 重試-CSDN博客
做個(gè)完善
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;
}
//默認(rèn)1.5秒重試一次
retryIntervalList.add(1500L);
}
/**
* 該方法提供了一個(gè)Chain類型的對(duì)象,Chain對(duì)象中可以獲取到Request對(duì)象
* ,而調(diào)用Chain對(duì)象的proceed方法(該方法接收一個(gè)Request對(duì)象)就可發(fā)起一次網(wǎng)絡(luò)請(qǐng)求
* ,該方法返回Response對(duì)象。
*
* @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);
}
}
}
解決多個(gè)BaseURL切換其他方案
解決Retrofit多BaseUrl及運(yùn)行時(shí)動(dòng)態(tài)改變BaseUrl? - 簡(jiǎn)書