gpt4 book ai didi

android - 如何在 Android 中使用 Retrofit 2.0 处理无网络连接?

转载 作者:行者123 更新时间:2023-11-30 01:13:21 24 4
gpt4 key购买 nike

我在我的 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
*/
}
});

即使 onResponse() 将被调用,如果我们得到状态代码为 4xx 或 5xx,那么我们也需要处理该情况。

我的问题是,如何通过在 Android 中使用 Retrofit 2.0 来区分请求失败的原因,即 onFailure()

最佳答案

Here my question is, How to differentiate reason for request failure by using Retrofit 2.0 in Android?

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

if (response.code() < 400) {

No Network connection 的情况下,调用 onFailure。在那里你可以检查可抛出的实例。通常是一个 IOException

关于android - 如何在 Android 中使用 Retrofit 2.0 处理无网络连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38206395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com