awo*_*rer 6 android retrofit retrofit2 okhttp3
如何使用Retrofit 2检测没有互联网连接错误?
我在Retrofit 1中曾经做的是实现Client接口并在execute(Request request)执行连接检查。
我在Retrofit 2中尝试的是:
public class RequestInterceptor implements Interceptor {
final ConnectivityManager connectivityManager;
@Inject
public RequestInterceptor(ConnectivityManager connectivityManager) {
this.connectivityManager = connectivityManager;
}
@Override
public Response intercept(Chain chain) throws IOException {
if (isConnected()) {
throw new OfflineException("no internet");
}
Request.Builder r = chain.request().newBuilder();
return chain.proceed(r.build());
}
protected boolean isConnected() {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
}
Run Code Online (Sandbox Code Playgroud)
我可以通过添加try-catch块来通过同步Retrofit执行来捕获它,但是不能通过异步(将错误作为OnFailure(Call call,Throwable t)的参数返回)进行异步捕获。应用程序因我在拦截器中抛出的OfflineException而崩溃。