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