使用OKHttp进行改造可以在离线时使用缓存数据
我正在尝试使用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);
这是带有Cache-Control标头的MyApi
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从缓存中读取响应吗?
编辑: 因为OKHttp 2.0.x HttpResponseCache
是Cache
,setResponseCache
是setCache
相关分类