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