• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package android.net.http;
18 
19 import com.android.okhttp.internalandroidapi.AndroidResponseCacheAdapter;
20 import com.android.okhttp.internalandroidapi.HasCacheHolder;
21 
22 import java.io.Closeable;
23 import java.io.File;
24 import java.io.IOException;
25 import java.net.CacheRequest;
26 import java.net.CacheResponse;
27 import java.net.ResponseCache;
28 import java.net.URI;
29 import java.net.URLConnection;
30 import java.util.List;
31 import java.util.Map;
32 
33 /**
34  * Caches HTTP and HTTPS responses to the filesystem so they may be reused,
35  * saving time and bandwidth. This class supports {@link
36  * java.net.HttpURLConnection} and {@link javax.net.ssl.HttpsURLConnection};
37  * there is no platform-provided cache for {@code DefaultHttpClient} or
38  * {@code AndroidHttpClient}. Installation and instances are thread
39  * safe.
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  */
151 public final class HttpResponseCache extends ResponseCache implements HasCacheHolder, Closeable {
152 
153     private final AndroidResponseCacheAdapter mDelegate;
154 
HttpResponseCache(AndroidResponseCacheAdapter delegate)155     private HttpResponseCache(AndroidResponseCacheAdapter delegate) {
156         mDelegate = 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      */
getInstalled()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      */
install(File directory, long maxSize)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             CacheHolder cacheHolder = installedResponseCache.getCacheHolder();
187             // don't close and reopen if an equivalent cache is already installed
188             if (cacheHolder.isEquivalent(directory, maxSize)) {
189                 return installedResponseCache;
190             } else {
191                 // The HttpResponseCache that owns this object is about to be replaced.
192                 installedResponseCache.close();
193             }
194         }
195 
196         CacheHolder cacheHolder = CacheHolder.create(directory, maxSize);
197         AndroidResponseCacheAdapter androidResponseCacheAdapter =
198                 new AndroidResponseCacheAdapter(cacheHolder);
199         HttpResponseCache responseCache = new HttpResponseCache(androidResponseCacheAdapter);
200         ResponseCache.setDefault(responseCache);
201         return responseCache;
202     }
203 
204     @Override
get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders)205     public CacheResponse get(URI uri, String requestMethod,
206             Map<String, List<String>> requestHeaders) throws IOException {
207         return mDelegate.get(uri, requestMethod, requestHeaders);
208     }
209 
210     @Override
put(URI uri, URLConnection urlConnection)211     public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
212         return mDelegate.put(uri, urlConnection);
213     }
214 
215     /**
216      * Returns the number of bytes currently being used to store the values in
217      * this cache. This may be greater than the {@link #maxSize} if a background
218      * deletion is pending. {@code -1} is returned if the size cannot be determined.
219      */
size()220     public long size() {
221         try {
222             return mDelegate.getSize();
223         } catch (IOException e) {
224             // This can occur if the cache failed to lazily initialize.
225             return -1;
226         }
227     }
228 
229     /**
230      * Returns the maximum number of bytes that this cache should use to store
231      * its data.
232      */
maxSize()233     public long maxSize() {
234         return mDelegate.getMaxSize();
235     }
236 
237     /**
238      * Force buffered operations to the filesystem. This ensures that responses
239      * written to the cache will be available the next time the cache is opened,
240      * even if this process is killed.
241      */
flush()242     public void flush() {
243         try {
244             mDelegate.flush();
245         } catch (IOException ignored) {
246         }
247     }
248 
249     /**
250      * Returns the number of HTTP requests that required the network to either
251      * supply a response or validate a locally cached response.
252      */
getNetworkCount()253     public int getNetworkCount() {
254         return mDelegate.getNetworkCount();
255     }
256 
257     /**
258      * Returns the number of HTTP requests whose response was provided by the
259      * cache. This may include conditional {@code GET} requests that were
260      * validated over the network.
261      */
getHitCount()262     public int getHitCount() {
263         return mDelegate.getHitCount();
264     }
265 
266     /**
267      * Returns the total number of HTTP requests that were made. This includes
268      * both client requests and requests that were made on the client's behalf
269      * to handle a redirects and retries.
270      */
getRequestCount()271     public int getRequestCount() {
272         return mDelegate.getRequestCount();
273     }
274 
275     /**
276      * Uninstalls the cache and releases any active resources. Stored contents
277      * will remain on the filesystem.
278      */
279     @Override
close()280     public void close() throws IOException {
281         if (ResponseCache.getDefault() == this) {
282             ResponseCache.setDefault(null);
283         }
284         mDelegate.close();
285     }
286 
287     /**
288      * Uninstalls the cache and deletes all of its stored contents.
289      */
delete()290     public void delete() throws IOException {
291         if (ResponseCache.getDefault() == this) {
292             ResponseCache.setDefault(null);
293         }
294         mDelegate.delete();
295     }
296 
297     /** @hide Needed for OkHttp integration. */
298     @Override
getCacheHolder()299     public CacheHolder getCacheHolder() {
300         return mDelegate.getCacheHolder();
301     }
302 }
303