【发布时间】:2016-11-07 11:10:22
【问题描述】:
我在我的 android 应用程序中使用 Retrofit 2.0 库,方法是将其添加到 build.gradle 文件中
// retrofit, gson
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
相关代码如下
ApiInterface.java
public interface ApiInterface {
@GET("contacts/")
Call<ContactsModel> getContactsList();
}
ApiClient.java
public class ApiClient {
public static final String BASE_URL = "http://myexamplebaseurl/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
MainActivity.java
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ContactsModel> call = apiService.getContactsList();
call.enqueue(new Callback<ContactsModel>() {
@Override
public void onResponse(Call<ContactsModel> call, Response<ContactsModel> response) {
if(response.isSuccessful()){
/*here is my data handling*/
}
}
@Override
public void onFailure(Call<ContactsModel> call, Throwable t) {
/*It is the request failure case,
I want to differentiate Request timeout, no internet connection and any other reason behind the request failure
*/
}
});
如果我们得到状态码为 4xx 或 5xx,即使 onResponse() 会被调用,那么我们也需要处理这种情况。
我的问题是,如何通过在 Android 中使用 Retrofit 2.0 来区分请求失败的原因,即onFailure()?
【问题讨论】:
标签: android web-services retrofit retrofit2 android-webservice