编辑改造2.x:
OkHttp Interceptor是脱机时访问缓存的正确方法:
1)创建拦截器:
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); if (Utils.isNetworkAvailable(context)) { 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(); } }
2)安装客户端:
OkHttpClient client = new OkHttpClient();client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);//setup cacheFile httpCacheDirectory = new File(context.getCacheDir(), "responses");int cacheSize = 10 * 1024 * 1024; // 10 MiBCache cache = new Cache(httpCacheDirectory, cacheSize);//add cache to the clientclient.setCache(cache);
3)将客户添加到改造中
Retrofit retrofit = new Retrofit.Builder() .baseUrl(base_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build();
另请检查@kosiara-Bartosz Kosarzycki的答案。您可能需要从响应中删除一些标头。
OKHttp 2.0.x(检查原始答案):
由于OKHttp 2.0.x HttpResponseCache是Cache,所以setResponseCache是setCache。因此,您应该setCache这样:
File httpCacheDirectory = new File(context.getCacheDir(), "responses"); Cache cache = null; try { cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024); } catch (IOException e) { Log.e("OKHttp", "Could not create http cache", e); } OkHttpClient okHttpClient = new OkHttpClient(); if (cache != null) { okHttpClient.setCache(cache); } String hostURL = context.getString(R.string.host_url); api = new RestAdapter.Builder() .setEndpoint(hostURL) .setClient(new OkClient(okHttpClient)) .setRequestInterceptor() .build() .create(MyApi.class);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)