/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net.http; import com.android.okhttp.Cache; import com.android.okhttp.AndroidShimResponseCache; import com.android.okhttp.OkCacheContainer; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.CacheRequest; import java.net.CacheResponse; import java.net.ResponseCache; import java.net.URI; import java.net.URLConnection; import java.util.List; import java.util.Map; /** * Caches HTTP and HTTPS responses to the filesystem so they may be reused, * saving time and bandwidth. This class supports {@link * java.net.HttpURLConnection} and {@link javax.net.ssl.HttpsURLConnection}; * there is no platform-provided cache for {@code DefaultHttpClient} or * {@code AndroidHttpClient}. Installation and instances are thread * safe. * *
{@code * protected void onCreate(Bundle savedInstanceState) { * ... * * 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); * } * } * * protected void onStop() { * ... * * HttpResponseCache cache = HttpResponseCache.getInstalled(); * if (cache != null) { * cache.flush(); * } * }}* This cache will evict entries as necessary to keep its size from exceeding * 10 MiB. The best cache size is application specific and depends on the size * and frequency of the files being downloaded. Increasing the limit may improve * the hit rate, but it may also just waste filesystem space! * *
For some applications it may be preferable to create the cache in the * external storage directory. There are no access controls on the * external storage directory so it should not be used for caches that could * contain private data. Although it often has more free space, * external storage is optional and—even if available—can disappear * during use. Retrieve the external cache directory using {@link * android.content.Context#getExternalCacheDir()}. If this method returns null, * your application should fall back to either not caching or caching on * non-external storage. If the external storage is removed during use, the * cache hit rate will drop to zero and ongoing cache reads will fail. * *
Flushing the cache forces its data to the filesystem. This ensures that * all responses written to the cache will be readable the next time the * activity starts. * *
The best way to improve the cache hit rate is by configuring the web * server to return cacheable responses. Although this client honors all HTTP/1.1 (RFC 2068) cache * headers, it doesn't cache partial responses. * *
{@code * connection.addRequestProperty("Cache-Control", "no-cache"); * }* If it is only necessary to force a cached response to be validated by the * server, use the more efficient {@code max-age=0} instead:
{@code * connection.addRequestProperty("Cache-Control", "max-age=0"); * }* *
{@code * try { * connection.addRequestProperty("Cache-Control", "only-if-cached"); * InputStream cached = connection.getInputStream(); * // the resource was cached! show it * } catch (FileNotFoundException e) { * // the resource was not cached * } * }* This technique works even better in situations where a stale response is * better than no response. To permit stale cached responses, use the {@code * max-stale} directive with the maximum staleness in seconds:
{@code * int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale * connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); * }* *
{@code * try { * File httpCacheDir = new File(context.getCacheDir(), "http"); * long httpCacheSize = 10 * 1024 * 1024; // 10 MiB * Class.forName("android.net.http.HttpResponseCache") * .getMethod("install", File.class, long.class) * .invoke(null, httpCacheDir, httpCacheSize); * } catch (Exception httpResponseCacheNotAvailable) { * }}*/ public final class HttpResponseCache extends ResponseCache implements Closeable, OkCacheContainer { private final AndroidShimResponseCache delegate; private HttpResponseCache(AndroidShimResponseCache delegate) { this.delegate = delegate; } /** * Returns the currently-installed {@code HttpResponseCache}, or null if * there is no cache installed or it is not a {@code HttpResponseCache}. */ public static HttpResponseCache getInstalled() { ResponseCache installed = ResponseCache.getDefault(); if (installed instanceof HttpResponseCache) { return (HttpResponseCache) installed; } return null; } /** * Creates a new HTTP response cache and sets it as the system default cache. * * @param directory the directory to hold cache data. * @param maxSize the maximum size of the cache in bytes. * @return the newly-installed cache * @throws IOException if {@code directory} cannot be used for this cache. * Most applications should respond to this exception by logging a * warning. */ public static synchronized HttpResponseCache install(File directory, long maxSize) throws IOException { ResponseCache installed = ResponseCache.getDefault(); if (installed instanceof HttpResponseCache) { HttpResponseCache installedResponseCache = (HttpResponseCache) installed; // don't close and reopen if an equivalent cache is already installed AndroidShimResponseCache trueResponseCache = installedResponseCache.delegate; if (trueResponseCache.isEquivalent(directory, maxSize)) { return installedResponseCache; } else { // The HttpResponseCache that owns this object is about to be replaced. trueResponseCache.close(); } } AndroidShimResponseCache trueResponseCache = AndroidShimResponseCache.create(directory, maxSize); HttpResponseCache newResponseCache = new HttpResponseCache(trueResponseCache); ResponseCache.setDefault(newResponseCache); return newResponseCache; } @Override public CacheResponse get(URI uri, String requestMethod, Map