我正在尝试使用Retrofit&OKHttp来缓存HTTP响应。我遵循了这个要点,并最终获得了以下代码:
File httpCacheDirectory = new File(context.getCacheDir(), "responses"); HttpResponseCache httpResponseCache = null; try { httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024 * 1024); } catch (IOException e) { Log.e("Retrofit", "Could not create http cache", e); } OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setResponseCache(httpResponseCache); api = new RestAdapter.Builder() .setEndpoint(API_URL) .setLogLevel(RestAdapter.LogLevel.FULL) .setClient(new OkClient(okHttpClient)) .build() .create(MyApi.class);
这是MyApi,带有Cache-Control标头
public interface MyApi { @Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=2419200") @GET("/api/v1/person/1/") void requestPerson( Callback<Person> callback );
首先,我在线请求并检查缓存文件。正确的JSON响应和标头在那里。但是,当我尝试离线请求时,我总是得到RetrofitError UnknownHostException。我还需要做些其他事情来使Retrofit从缓存中读取响应吗?
RetrofitError UnknownHostException
编辑: 由于OKHttp 2.0.x HttpResponseCache是Cache,setResponseCache是setCache
OKHttp 2.0.x HttpResponseCache
Cache,setResponseCache
setCache
编辑改造2.x:
OkHttp Interceptor是脱机时访问缓存的正确方法:
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 cache File httpCacheDirectory = new File(context.getCacheDir(), "responses"); int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(httpCacheDirectory, cacheSize); //add cache to the client client.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(/*rest of the answer here */) .build() .create(MyApi.class);