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