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( ...
随机推荐
- (转)OpenVPN使用HTTP代理连接服务器
原文地址:http://www.365mini.com/page/18.htm 在一些公司或者其他受限的网络环境中,使用的是HTTP代理服务器上网.在这种情况下,使用OpenVPN客户端可能无法连接服 ...
- 学点css基础
中午时间学点css,附带http://www.w3cschool.cc/css/css-tutorial.html这个链接! 中午的时间学了这些东西!如下图: 附带代码: <!DOCTYPE h ...
- (转) ASP.NET页面缓存
原文:http://www.cnblogs.com/Sky_KWolf/archive/2010/12/05/1897158.html 静态页面全部内容保存在服务器内存中.当再有请求时,系统将缓存中的 ...
- LINQ里的Distinct()
IQueryable 继承自IEnumerable 先举例: #region linq to object List<People> peopleList = new List<Pe ...
- swift-06-字符串,字符以及元组类型
1.字符串和字符类型 //在swift中,字符串使用一对双引号括起来 var str = "hello M.SD-DJ" print(str) //字符也要用双引号括起来,用cha ...
- postgres create table default now
key_time timestamp without time zone default timestamp 'now()' see http://wordpress.factj.com/
- C语言链表全操作(增,删,改,查,逆序,递增排序,递减排序,链式队列,链式栈)
一,数据结构——链表全操作: 链表形式: 其中,每个节点(Node)是一个结构体,这个结构体包含数据域,指针域,数据域用来存放数据,指针域则用来指向下一个节点: 特别说明:对于单链表,每个节点(Nod ...
- C++ map插入(insert)数据返回值
例子: typedef boost::unordered_map<int, int> UserOnlineMap; UserOnlineMap userOnlineMap_; std::p ...
- jsonp多次请求报错 not a function的解决方法
添加时间戳给callbackId $.ajax({ type: "get", url: url, timeout: 6000, data: param, cache: false, ...
- html中th 与thead tbody的 使用
上午工作的时候,遇到一挺纠结的问题,在<th width...> width根本不起作用. 后来才明白<th>标签不能写在<tbody>里,不符合语法. 所以顺便总 ...