如何在Retrofit 2中检测无网络连接错误?
在Retrofit 1中,我通常是实现Client接口并在执行(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();
}
}
如果使用同步的Retrofit执行,您可以添加try-catch块来捕获错误,但是异步执行时会将错误作为OnFailure(Call call, Throwable t)方法的参数返回。当我在拦截器中抛出OfflineException时,应用程序会崩溃。
chain.proceed(chain.request())
即可。 - Paul Woitaschek