How to use an installed HttpResponseCache

721 Views Asked by At

I've followed the developers guide and I've installed an HttpResponseCache by including the following code in the onCreate() method of my application:

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);      
}

Now, at some point I launch an activity in this application and fetch a URL using the following code:

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();
}

Do I have to do something when I fetch the URL to tell it to use the installed cache? Or will any activity launched inside this application automatically use it?

For example, in this example code they call connection.setUseCaches(true). Is that necessary?

1

There are 1 best solutions below

2
On BEST ANSWER

The installed HttpResponseCache will be used by HttpURLConnection and HttpsURLConnection as long as you call setUseCaches(true) on the connection.

Also the response from the web server needs to be cacheable.