android离线时如何调用API?
How to call API when offline in android?
当互联网连接可用时,我成功地调用了 API,
当没有互联网连接时,我如何调用相同的 API?
基本上,
我想知道在线和离线同步?
用户可以在其中添加数据,但只有在互联网可用时才会将其推送到服务器。
我该怎么做?
如果你消费REST服务,你可以阅读this article about how to use manage offline with Retrofit。它是关于使用 Retrofit 实现的客户端。如果你使用了Volley,你可以参考这篇文章,看看如何实现一个基于OkHttp的缓存系统,Volley也是用的。
我在这里报告一部分代码。阅读本文以获得完整代码并根据您的需要进行调整。
// Add all interceptors you want (headers, URL, logging, stetho logs)
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache());
...
private Interceptor provideOfflineCacheInterceptor() {
return chain -> {
Request request = chain.request();
if (!isConnected()) {
CacheControl cacheControl = new CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build();
request = request.newBuilder()
.removeHeader(HEADER_PRAGMA)
.removeHeader(HEADER_CACHE_CONTROL)
.cacheControl(cacheControl)
.build();
}
return chain.proceed(request);
};
}
当互联网连接可用时,我成功地调用了 API, 当没有互联网连接时,我如何调用相同的 API?
基本上, 我想知道在线和离线同步? 用户可以在其中添加数据,但只有在互联网可用时才会将其推送到服务器。 我该怎么做?
如果你消费REST服务,你可以阅读this article about how to use manage offline with Retrofit。它是关于使用 Retrofit 实现的客户端。如果你使用了Volley,你可以参考这篇文章,看看如何实现一个基于OkHttp的缓存系统,Volley也是用的。
我在这里报告一部分代码。阅读本文以获得完整代码并根据您的需要进行调整。
// Add all interceptors you want (headers, URL, logging, stetho logs)
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache());
...
private Interceptor provideOfflineCacheInterceptor() {
return chain -> {
Request request = chain.request();
if (!isConnected()) {
CacheControl cacheControl = new CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build();
request = request.newBuilder()
.removeHeader(HEADER_PRAGMA)
.removeHeader(HEADER_CACHE_CONTROL)
.cacheControl(cacheControl)
.build();
}
return chain.proceed(request);
};
}