HttpResponseCache 网络缓存使用
Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth. This class supports HttpURLConnection
andHttpsURLConnection
; there is no platform-provided cache for DefaultHttpClient
or AndroidHttpClient
.
Installing an HTTP response cache 添加于 API 级别 13
Enable caching of all of your application's HTTP requests by installing the cache at application startup. For example, this code installs a 10 MiB cache in theapplication-specific cache directory
of the filesystem}:
protected void onCreate(Bundle savedInstanceState) {
catch (IOException e) {
...
try {
File httpCacheDir = new File(context.getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
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 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.
Cache Optimization
To measure cache effectiveness, this class tracks three statistics:
Request Count:
the number of HTTP requests issued since this cache was created.Network Count:
the number of those requests that required network use.Hit Count:
the number of those requests whose responses were served by the cache.
Sometimes a request will result in a conditional cache hit. If the cache contains a stale copy of the response, the client will issue a conditional GET
. The server will then send either the updated response if it has changed, or a short 'not modified' response if the client's copy is still valid. Such responses increment both the network count and hit count.
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.
Force a Network Response
In some situations, such as after a user clicks a 'refresh' button, it may be necessary to skip the cache, and fetch data directly from the server. To force a full refresh, add the no-cache
directive:
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 max-age=0
instead:
connection.addRequestProperty("Cache-Control", "max-age=0");
Force a Cache Response
Sometimes you'll want to show resources if they are available immediately, but not otherwise. This can be used so your application can show something while waiting for the latest data to be downloaded. To restrict a request to locally-cached resources, add the only-if-cached
directive:
try {
catch (FileNotFoundException e) {
connection.addRequestProperty("Cache-Control", "only-if-cached");
InputStream cached = connection.getInputStream();
// the resource was cached! show it
// 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 max-stale
directive with the maximum staleness in seconds:
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
connection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
Working With Earlier Releases
This class was added in Android 4.0 (Ice Cream Sandwich). Use reflection to enable the response cache without impacting earlier releases:
try {
catch (Exception httpResponseCacheNotAvailable) {
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);
}}
HttpResponseCache 网络缓存使用的更多相关文章
- NSCache和NSURLCache、网络缓存优化
本文目录 一种缓存优化方案 响应头'Last-Modified'和请求头'If-Modified-Since' 'Keep-Alive'响应头和不离线的URLSession 'Expires'响应头 ...
- 使用Retrofit和Okhttp实现网络缓存。无网读缓存,有网根据过期时间重新请求 (转)
使用Retrofit和Okhttp实现网络缓存,更新于2016.02.02原文链接:http://www.jianshu.com/p/9c3b4ea108a7 本文使用 Retrofit2.0.0-b ...
- android 项目学习随笔六(网络缓存)
1. 对SharePreference的封装 import android.content.Context; import android.content.SharedPreferences; /** ...
- 使用HttpURLConnection和AsyncTask从网络缓存图片
1.创建NetCacheUtils中创建downloadBitmap(String url)方法 private Bitmap downloadBitmap(String url){ HttpURLC ...
- Android公共库——图片缓存 网络缓存 下拉及底部更多ListView 公共类
Android公共库——图片缓存 网络缓存 下拉及底部更多ListView 公共类 转载自http://www.trinea.cn/android/android-common-lib/ 介绍总结的一 ...
- 【Swift】 GET&POST请求 网络缓存的简单处理
GET & POST 的对比 源码:https://github.com/SpongeBob-GitHub/Get-Post.git 1. URL - GET 所有的参数都包含在 URL 中 ...
- iOS 网络缓存总结
一.缓存策略: 1.缓存策略的配置: 缺省缓存策略的存储策略需要服务器的响应配置: 缺省缓存策略的使用需要请求端的配置: 2.缓存策略的缺陷: 移动端比较通用的缓存策略是先使用缓存同时更新本地数据: ...
- Android网络缓存的实现思路
在开发群里有多位同学问到了关于Android中网络缓存的问题.事实上不管是Android还是iOS,缓存的大致思路都是同样的,以下就几种情况下的缓存做一个大致的介绍.顺便说一下有些开源的网络请求框架已 ...
- 【Java/Android性能优 7】Android公共库——图片缓存 网络缓存 下拉及底部更多ListView 公共类
本文转自:http://www.trinea.cn/android/android-common-lib/ 介绍总结的一些android公共库,包含缓存(图片缓存.预取缓存.网络缓存).公共View( ...
随机推荐
- Asp.NET获取文件及其路径
[相对路径] Request.ApplicationPath /src Path.GetDirectoryName(HttpContext.Current.Request.RawUrl ) //s ...
- Atom编辑器入门到精通(五) Git支持
版本控制对于开发来说非常重要,Atom当然也提供了很好的支持,本文将介绍如何在Atom中集成使用Git和GitHub 恢复文件 当你修改了某个文件,然后发现改得不满意,希望恢复文件到最后一次提交的状态 ...
- postgresql行转列并拼接字符串
有这样一张表: ; id | kw ----+-------- 1 | big 1 | hello 2 | oracle 2 | small 2 | apple 3 | shit( ...
- UIAlertController基本使用
从ios8之后,系统的弹框 UIAlertView 与 UIActionSheet 两个并在一了起, 使用了一个新的控制器叫 UIAlertController UIAlertController ...
- java.util.HashMap源码分析
在java jdk8中对HashMap的源码进行了优化,在jdk7中,HashMap处理“碰撞”的时候,都是采用链表来存储,当碰撞的结点很多时,查询时间是O(n). 在jdk8中,HashMap处理“ ...
- SVN资料库转移-----dump和load
最近由于大批量的更换服务器,所以之前布署的SVN服务器需要重新布署,需要把原来的资源库转移到新服务器上,并且使管理的项目版本一致,在网上查了一下SVN版本库迁移,但看了一上google出来的也很少,所 ...
- python的一个表达式的计算(超简单)
运行的过程如下: 输入计算表达式:3+5 计算结果:8 然后再次显示计算表达式,等待输入完成后,再次显示结果,依此循环. 作为初学者再适合不过,代码也简单,如下所示: #!/usr/bin/env ...
- javascript 事件对象
1.事件对象 用来记录一些事件发生时的相关信息的对象 A.只有当事件发生的时候才产生,只能在处理函数内部访问 B.处理函数运行结束后自动销毁2.如何获取事件对象 IE: window.even ...
- yii2 安装
php版本必须是php5.4以上.记得配置php环境变量 1.下载https://github.com/yiisoft/yii2-app-advanced 2.php -r "readfil ...
- TDirectory.GetFileSystemEntries获取指定目录下的目录和文件
使用函数: System.IOUtils.TDirectory.GetFileSystemEntries 所有重载: class function GetFileSystemEntries(const ...