Retrofit 与 OKHttp 可以在离线时利用缓存数据吗?
在尝试使用 Retrofit 和 OKHttp 缓存 HTTP 响应时,您遇到了以下问题离线时获取 RetrofitError UnknownHostException。这表明 Retrofit 无法检索缓存的数据。要解决此问题,需要进行以下修改:
针对 Retrofit 2.x 进行编辑:
实现 OkHttp 拦截器来管理缓存逻辑:
<code class="java">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(); } } }</code>
为 OkHttpClient 配置拦截器和缓存:
<code class="java">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);</code>
将 OkHttpClient 与 Retrofit 集成:
<code class="java">Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build();</code>
OKHttp 2.0.x:
调整您的客户端设置以反映更新的语法:
<code class="java"> 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); } ...</code>
原始答案:
实现一个请求拦截器,根据网络可用性设置 Cache-Control 标头:
<code class="java">RestAdapter.Builder builder= new RestAdapter.Builder() .setRequestInterceptor(new RequestInterceptor() { @Override public void intercept(RequestFacade request) { request.addHeader("Accept", "application/json;versions=1"); if (MyApplicationUtils.isNetworkAvailable(context)) { int maxAge = 60; // read from cache for 1 minute request.addHeader("Cache-Control", "public, max-age=" + maxAge); } else { int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale request.addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale); } } });</code>
通过实现这些修改,Retrofit 将在离线时正确利用缓存数据,如下所示只要服务器响应包含适当的缓存控制标头。
以上是OKHttp改造可以在离线时利用缓存数据吗?的详细内容。更多信息请关注PHP中文网其他相关文章!