如何使用已安装的 HttpResponseCache

Posted

技术标签:

【中文标题】如何使用已安装的 HttpResponseCache【英文标题】:How to use an installed HttpResponseCache 【发布时间】:2014-08-16 14:59:45 【问题描述】:

我遵循developers guide 并通过在我的应用程序的 onCreate() 方法中包含以下代码安装了 HttpResponseCache:

try 
  File httpCacheDir = new File(context.getCacheDir(), "http");
  long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
  HttpResponseCache.install(httpCacheDir, httpCacheSize);
   catch (IOException e) 
       Log.i(TAG, "HTTP response cache installation failed:" + e);      

现在,有时我会在此应用程序中启动一个活动并使用以下代码获取 URL:

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try 
  InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  readStream(in);
 finally 
  urlConnection.disconnect();

当我获取 URL 以告诉它使用已安装的缓存时,我是否必须做一些事情?或者在这个应用程序中启动的任何活动都会自动使用它?

例如,在this example code 中,他们调用connection.setUseCaches(true)。有必要吗?

【问题讨论】:

【参考方案1】:

只要在连接上调用setUseCaches(true)HttpURLConnectionHttpsURLConnection 就会使用安装的HttpResponseCache。

来自网络服务器的响应也需要可缓存。

【讨论】:

我已经使用 HTTPClient 进行请求。我如何在这里使用 HttpResponseCatch? setUseCaches(true) 是不必要的

以上是关于如何使用已安装的 HttpResponseCache的主要内容,如果未能解决你的问题,请参考以下文章