HttpResponseCache.java revision 3bdd327f8532a79b83f575cc62e8eb09a1f93f3d
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net.http;
18
19import com.android.okhttp.Cache;
20import com.android.okhttp.AndroidShimResponseCache;
21import com.android.okhttp.OkCacheContainer;
22
23import java.io.Closeable;
24import java.io.File;
25import java.io.IOException;
26import java.net.CacheRequest;
27import java.net.CacheResponse;
28import java.net.ResponseCache;
29import java.net.URI;
30import java.net.URLConnection;
31import java.util.List;
32import java.util.Map;
33
34/**
35 * Caches HTTP and HTTPS responses to the filesystem so they may be reused,
36 * saving time and bandwidth. This class supports {@link
37 * java.net.HttpURLConnection} and {@link javax.net.ssl.HttpsURLConnection};
38 * there is no platform-provided cache for {@code DefaultHttpClient} or
39 * {@code AndroidHttpClient}.
40 *
41 * <h3>Installing an HTTP response cache</h3>
42 * Enable caching of all of your application's HTTP requests by installing the
43 * cache at application startup. For example, this code installs a 10 MiB cache
44 * in the {@link android.content.Context#getCacheDir() application-specific
45 * cache directory} of the filesystem}: <pre>   {@code
46 *   protected void onCreate(Bundle savedInstanceState) {
47 *       ...
48 *
49 *       try {
50 *           File httpCacheDir = new File(context.getCacheDir(), "http");
51 *           long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
52 *           HttpResponseCache.install(httpCacheDir, httpCacheSize);
53 *       } catch (IOException e) {
54 *           Log.i(TAG, "HTTP response cache installation failed:" + e);
55 *       }
56 *   }
57 *
58 *   protected void onStop() {
59 *       ...
60 *
61 *       HttpResponseCache cache = HttpResponseCache.getInstalled();
62 *       if (cache != null) {
63 *           cache.flush();
64 *       }
65 *   }}</pre>
66 * This cache will evict entries as necessary to keep its size from exceeding
67 * 10 MiB. The best cache size is application specific and depends on the size
68 * and frequency of the files being downloaded. Increasing the limit may improve
69 * the hit rate, but it may also just waste filesystem space!
70 *
71 * <p>For some applications it may be preferable to create the cache in the
72 * external storage directory. <strong>There are no access controls on the
73 * external storage directory so it should not be used for caches that could
74 * contain private data.</strong> Although it often has more free space,
75 * external storage is optional and&#8212;even if available&#8212;can disappear
76 * during use. Retrieve the external cache directory using {@link
77 * android.content.Context#getExternalCacheDir()}. If this method returns null,
78 * your application should fall back to either not caching or caching on
79 * non-external storage. If the external storage is removed during use, the
80 * cache hit rate will drop to zero and ongoing cache reads will fail.
81 *
82 * <p>Flushing the cache forces its data to the filesystem. This ensures that
83 * all responses written to the cache will be readable the next time the
84 * activity starts.
85 *
86 * <h3>Cache Optimization</h3>
87 * To measure cache effectiveness, this class tracks three statistics:
88 * <ul>
89 *     <li><strong>{@link #getRequestCount() Request Count:}</strong> the number
90 *         of HTTP requests issued since this cache was created.
91 *     <li><strong>{@link #getNetworkCount() Network Count:}</strong> the
92 *         number of those requests that required network use.
93 *     <li><strong>{@link #getHitCount() Hit Count:}</strong> the number of
94 *         those requests whose responses were served by the cache.
95 * </ul>
96 * Sometimes a request will result in a conditional cache hit. If the cache
97 * contains a stale copy of the response, the client will issue a conditional
98 * {@code GET}. The server will then send either the updated response if it has
99 * changed, or a short 'not modified' response if the client's copy is still
100 * valid. Such responses increment both the network count and hit count.
101 *
102 * <p>The best way to improve the cache hit rate is by configuring the web
103 * server to return cacheable responses. Although this client honors all <a
104 * href="http://www.ietf.org/rfc/rfc2616.txt">HTTP/1.1 (RFC 2068)</a> cache
105 * headers, it doesn't cache partial responses.
106 *
107 * <h3>Force a Network Response</h3>
108 * In some situations, such as after a user clicks a 'refresh' button, it may be
109 * necessary to skip the cache, and fetch data directly from the server. To force
110 * a full refresh, add the {@code no-cache} directive: <pre>   {@code
111 *         connection.addRequestProperty("Cache-Control", "no-cache");
112 * }</pre>
113 * If it is only necessary to force a cached response to be validated by the
114 * server, use the more efficient {@code max-age=0} instead: <pre>   {@code
115 *         connection.addRequestProperty("Cache-Control", "max-age=0");
116 * }</pre>
117 *
118 * <h3>Force a Cache Response</h3>
119 * Sometimes you'll want to show resources if they are available immediately,
120 * but not otherwise. This can be used so your application can show
121 * <i>something</i> while waiting for the latest data to be downloaded. To
122 * restrict a request to locally-cached resources, add the {@code
123 * only-if-cached} directive: <pre>   {@code
124 *     try {
125 *         connection.addRequestProperty("Cache-Control", "only-if-cached");
126 *         InputStream cached = connection.getInputStream();
127 *         // the resource was cached! show it
128 *     } catch (FileNotFoundException e) {
129 *         // the resource was not cached
130 *     }
131 * }</pre>
132 * This technique works even better in situations where a stale response is
133 * better than no response. To permit stale cached responses, use the {@code
134 * max-stale} directive with the maximum staleness in seconds: <pre>   {@code
135 *         int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
136 *         connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
137 * }</pre>
138 *
139 * <h3>Working With Earlier Releases</h3>
140 * This class was added in Android 4.0 (Ice Cream Sandwich). Use reflection to
141 * enable the response cache without impacting earlier releases: <pre>   {@code
142 *       try {
143 *           File httpCacheDir = new File(context.getCacheDir(), "http");
144 *           long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
145 *           Class.forName("android.net.http.HttpResponseCache")
146 *                   .getMethod("install", File.class, long.class)
147 *                   .invoke(null, httpCacheDir, httpCacheSize);
148 *       } catch (Exception httpResponseCacheNotAvailable) {
149 *       }}</pre>
150 */
151public final class HttpResponseCache extends ResponseCache implements Closeable, OkCacheContainer {
152
153    private final AndroidShimResponseCache delegate;
154
155    private HttpResponseCache(AndroidShimResponseCache delegate) {
156        this.delegate = delegate;
157    }
158
159    /**
160     * Returns the currently-installed {@code HttpResponseCache}, or null if
161     * there is no cache installed or it is not a {@code HttpResponseCache}.
162     */
163    public static HttpResponseCache getInstalled() {
164        ResponseCache installed = ResponseCache.getDefault();
165        if (installed instanceof HttpResponseCache) {
166            return (HttpResponseCache) installed;
167        }
168        return null;
169    }
170
171    /**
172     * Creates a new HTTP response cache and sets it as the system default cache.
173     *
174     * @param directory the directory to hold cache data.
175     * @param maxSize the maximum size of the cache in bytes.
176     * @return the newly-installed cache
177     * @throws IOException if {@code directory} cannot be used for this cache.
178     *     Most applications should respond to this exception by logging a
179     *     warning.
180     */
181    public static synchronized HttpResponseCache install(File directory, long maxSize)
182            throws IOException {
183        ResponseCache installed = ResponseCache.getDefault();
184        if (installed instanceof HttpResponseCache) {
185            HttpResponseCache installedResponseCache = (HttpResponseCache) installed;
186            // don't close and reopen if an equivalent cache is already installed
187            AndroidShimResponseCache trueResponseCache = installedResponseCache.delegate;
188            if (trueResponseCache.isEquivalent(directory, maxSize)) {
189                return installedResponseCache;
190            } else {
191                // The HttpResponseCache that owns this object is about to be replaced.
192                trueResponseCache.close();
193            }
194        }
195
196        AndroidShimResponseCache trueResponseCache =
197                AndroidShimResponseCache.create(directory, maxSize);
198        HttpResponseCache newResponseCache = new HttpResponseCache(trueResponseCache);
199        ResponseCache.setDefault(newResponseCache);
200        return newResponseCache;
201    }
202
203    @Override public CacheResponse get(URI uri, String requestMethod,
204            Map<String, List<String>> requestHeaders) throws IOException {
205        return delegate.get(uri, requestMethod, requestHeaders);
206    }
207
208    @Override public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
209        return delegate.put(uri, urlConnection);
210    }
211
212    /**
213     * Returns the number of bytes currently being used to store the values in
214     * this cache. This may be greater than the {@link #maxSize} if a background
215     * deletion is pending. {@code -1} is returned if the size cannot be determined.
216     */
217    public long size() {
218        try {
219            return delegate.size();
220        } catch (IOException e) {
221            // This can occur if the cache failed to lazily initialize.
222            return -1;
223        }
224    }
225
226    /**
227     * Returns the maximum number of bytes that this cache should use to store
228     * its data.
229     */
230    public long maxSize() {
231        return delegate.maxSize();
232    }
233
234    /**
235     * Force buffered operations to the filesystem. This ensures that responses
236     * written to the cache will be available the next time the cache is opened,
237     * even if this process is killed.
238     */
239    public void flush() {
240        try {
241            delegate.flush();
242        } catch (IOException ignored) {
243        }
244    }
245
246    /**
247     * Returns the number of HTTP requests that required the network to either
248     * supply a response or validate a locally cached response.
249     */
250    public int getNetworkCount() {
251        return delegate.getNetworkCount();
252    }
253
254    /**
255     * Returns the number of HTTP requests whose response was provided by the
256     * cache. This may include conditional {@code GET} requests that were
257     * validated over the network.
258     */
259    public int getHitCount() {
260        return delegate.getHitCount();
261    }
262
263    /**
264     * Returns the total number of HTTP requests that were made. This includes
265     * both client requests and requests that were made on the client's behalf
266     * to handle a redirects and retries.
267     */
268    public int getRequestCount() {
269        return delegate.getRequestCount();
270    }
271
272    /**
273     * Uninstalls the cache and releases any active resources. Stored contents
274     * will remain on the filesystem.
275     */
276    @Override public void close() throws IOException {
277        if (ResponseCache.getDefault() == this) {
278            ResponseCache.setDefault(null);
279        }
280        delegate.close();
281    }
282
283    /**
284     * Uninstalls the cache and deletes all of its stored contents.
285     */
286    public void delete() throws IOException {
287        if (ResponseCache.getDefault() == this) {
288            ResponseCache.setDefault(null);
289        }
290        delegate.delete();
291    }
292
293    /** @hide Needed for OkHttp integration. */
294    @Override
295    public Cache getCache() {
296        return delegate.getCache();
297    }
298
299}
300