
前言:
前面提到 Retrofit與Rxjava 的結(jié)合使用 ,今天我們就來說一說Retrofit原生自帶的Call接口的使用,本文主要針對Retrofit 2.0 的開發(fā)使用,對于2.0之前的版本的使用不做討論。
1.添加INTERNET權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
在Retrofit 2.0中,當(dāng)你調(diào)用call.enqueue或者call.execute,未添加權(quán)限,將立即拋出SecurityException,如果你不使用try-catch會導(dǎo)致崩潰。
2.Call 接口的實(shí)例化
public interface GitHubService {
@GET("list")
Call<List<Repo>> listRepos();
}
創(chuàng)建service 的方法和OkHttp的模式一模一樣。
GitHubService service = retrofit.create(GitHubService.class);
如果要調(diào)用同步請求,只需調(diào)用execute;而發(fā)起一個(gè)異步請求則是調(diào)用enqueue。
3.同步請求
Call<List<Repo>> call = service. listRepos();
List<Repo> repo = call.execute();
以上的代碼會阻塞線程,因此你不能在安卓的主線程中調(diào)用,不然會面臨NetworkOnMainThreadException。如果你想調(diào)用execute方法,請?jiān)陂_啟子線程執(zhí)行。
4.異步請求
Call<Repo> call = service.listRepos("user");
call.enqueue(new Callback<Repo>() {
@Override
public void onResponse(Call<List<Repo>> call,Response<List<Repo>> response) {
// Get result Repo from response.body()
}
@Override
public void onFailure(Call<List<Repo>> call,Throwable t) {
}
});
以上代碼發(fā)起了一個(gè)在后臺線程的請求并從response 的response.body()方法中獲取一個(gè)結(jié)果對象。注意這里的onResponse和onFailure方法是在主線程中調(diào)用的。
這里建議你使用enqueue,它最符合 Android OS的習(xí)慣。
5.取消正在進(jìn)行中的業(yè)務(wù)
service 的模式變成Call的形式的原因是為了讓正在進(jìn)行的事務(wù)可以被取消。要做到這點(diǎn),你只需調(diào)用call.cancel()。
call.cancel();
6.Callback 回調(diào)的使用
onResponse的調(diào)用,不僅僅是成功返回結(jié)果時(shí)調(diào)用,存在問題時(shí)也會被調(diào)用,這里查看了很多關(guān)于出現(xiàn)這個(gè)問題的解決方法,然而并沒有給出一個(gè)明確的方案,之后查看了一下Retrofit2.0 提供的官方API解釋,如下:
An HTTP response may still indicate an application-level failure such as a 404 or 500. Call Response.isSuccessful() to determine if the response indicates success.
HTTP response 仍然可以指示應(yīng)用程序級故障,如404或500。調(diào)用Response.isSuccessful(),以確定是否該響應(yīng)指示成功。
@Override
public void onResponse(Call<List<Repo>> call,Response<List<Repo>> response) {
// Get result Repo from response.body()
if(response.isSuccessful()){
List<Repo> repos = response.body();
//對數(shù)據(jù)的處理操作
}else{
//請求出現(xiàn)錯誤例如:404 或者 500
}
}
而關(guān)于 onFailure方法的調(diào)用,網(wǎng)上也并沒有給出明確的調(diào)用時(shí)機(jī),而官方文檔給出解釋:
Invoked when a network exception occurred talking to the server or when an unexpected exception occurred creating the request or processing the response.
當(dāng)連接服務(wù)器時(shí)出現(xiàn)網(wǎng)絡(luò)異常 或者 在創(chuàng)建請求、處理響應(yīng)結(jié)果 的時(shí)候突發(fā)異常 都會被調(diào)用。
通過自己測試發(fā)現(xiàn)了幾種調(diào)用情況:GSON解析數(shù)據(jù)轉(zhuǎn)換錯誤,手機(jī)斷網(wǎng)或者網(wǎng)絡(luò)異常。
@Override
public void onFailure(Call<List<Repo>> call,Throwable t) {
}