【发布时间】:2017-05-09 16:39:54
【问题描述】:
该类包含用于调用 API 的 APIClient 实例,但在获取缓存时存在一个问题。我想在设备未连接到网络时从缓存中获取数据。
private static Retrofit retrofit = null;
private static final String CACHE_CONTROL = "Cache-Control";
public static Retrofit getClient(Context context)
{
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(URLS.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(provideOkHttpClient(context))
.build();
}
return retrofit;
}
/**
* Add Client for adding Authentication headers.
* @return Retrofit
*/
public static Retrofit getAthenticationClient()
{
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(URLS.BASE_URL)
.client(ApiIntercepters.AddAuthenticationHeader())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
public static OkHttpClient provideOkHttpClient(Context context)
{
return new OkHttpClient.Builder()
.addNetworkInterceptor(provideCacheInterceptor())
.cache( provideCache(context))
.build();
}
private static Cache provideCache (Context context)
{
Cache cache = null;
try
{
//setup cache
File httpCacheDirectory = new File(context.getCacheDir(), "responses");
int cacheSize = 10 * 1024 * 1024; // 10 MiB
cache = new Cache(httpCacheDirectory, cacheSize);
}
catch (Exception e)
{
Log.e( "Injector :-> ", "Could not create Cache!" );
}
return cache;
}
public static Interceptor provideCacheInterceptor ()
{
return new Interceptor()
{
@Override
public Response intercept (Chain chain) throws IOException
{
Response originalResponse = chain.proceed(chain.request());
if (RetrofitDemoApp.hasNetwork()) {
int maxAge = 60; // read from cache for 1 minute
return originalResponse.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
return originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
}
};
}
【问题讨论】:
-
为什么在检索数据时不保存数据以备后用?
-
您能告诉我如何在改造中使用高速缓存保存数据吗?我是 Retrofit 缓存管理的新手。
-
谢谢!!!我正在获得解决方案,但在获得响应时,我在离线模式下收到 504 错误:@Override public void onResponse(Call
call, Response response) { parameters.DismissLoader();尝试 { if (response.code() == 200) { GetRegisterResponse(response.body().string()); } } catch (IOException e) { e.printStackTrace(); } -
表示网关超时。我的猜测是你在你的 URL 中犯了一个错误,遗漏了一个符号或空格或一些微不足道的东西。当您调试 onResponse 方法时,请查看响应对象并复制 URL。在网络浏览器中测试上述 URL,看看它是否正常工作。即你得到你想要的回应。
标签: android api response retrofit okhttp