我在我的安卓应用程序中使用Retroeft2.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()
会调用,那么我们也需要处理这个条件。
在这里,我的问题是,如何区分请求失败的原因,即onFailure()
通过在安卓系统中使用Retroeft2.0?
发布于 2016-07-05 06:47:30
这里我的问题是,如何通过在Android中使用Retroeft2.0来区分请求失败的原因?
如果您有4xx或5xx错误,则仍将调用onResponse
。在那里,您必须检查代码的响应代码,以检查是否一切正常。E.g
if (response.code() < 400) {
在No Network connection
的情况下,调用onFailure
。在那里,您可以检查throwable的实例。典型的IOException
https://stackoverflow.com/questions/38206395
复制相似问题