首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何在Android中使用Retroeft2.0处理无网络连接?

如何在Android中使用Retroeft2.0处理无网络连接?
EN

Stack Overflow用户
提问于 2016-07-05 06:44:19
回答 1查看 4.1K关注 0票数 1

我在我的安卓应用程序中使用Retroeft2.0库,将它添加到build.gradle文件中

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// 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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public interface ApiInterface {
   @GET("contacts/")
   Call<ContactsModel> getContactsList();
}

ApiClient.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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?

EN

回答 1

Stack Overflow用户

发布于 2016-07-05 06:47:30

这里我的问题是,如何通过在Android中使用Retroeft2.0来区分请求失败的原因?

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
if (response.code() < 400) {

No Network connection的情况下,调用onFailure。在那里,您可以检查throwable的实例。典型的IOException

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38206395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文