【问题标题】:How to handle No Network connection using Retrofit 2.0 in Android?如何在 Android 中使用 Retrofit 2.0 处理无网络连接?
【发布时间】: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


    【解决方案1】:

    我的问题是,如何区分请求失败的原因 在 Android 中使用 Retrofit 2.0?

    如果您有 4xx 或 5xx 错误,onResponse 仍会被调用。在那里,您必须检查代码的响应代码以检查一切是否正常。例如

    if (response.code() < 400) {
    

    如果是No Network connection,则调用onFailure。在那里你可以检查 throwable 的实例。通常是 IOException

    【讨论】:

    • 感谢您的回复。我同意您的观点“4xx 或 5xx 错误,仍然调用 onResponse”,您的意思是说如果该异常是 IOException 类型,那么是“无网络连接”吗?
    • 确实如此。查看 IOException 的直接子类here
    • 我想说的不仅仅是“没有网络连接”,还有问题到达服务器。
    • 如果远程服务器关闭或设备没有互联网,在这两种情况下你都会得到IOException。我们如何向用户显示常见消息“无网络连接”。我们如何区分这两者。
    • @Madhu 你必须检查 IOExcepiton 的实例
    猜你喜欢
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 2014-10-02
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    相关资源
    最近更新 更多