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( ...
随机推荐
- 如何在网页上显示html代码?
a: 把代码写在文本区域 <textarea> 标签中.可以设置 disabled="disabled" 属性,禁止用户操作.b: 把要显示在html文档中标签的 &q ...
- 并行计算vs分布式计算
一般认为,集中在同一个机柜内或同一个地点的紧密耦合多处理机系统或大规模并行处理系统是并行处理系统,而用局域网或广域网连接的计算机系统是分布式处理系统.松散耦合并行计算机中的并行操作系统有时也称为分布式 ...
- 详说C#中的结构struct
一.结构和类的区别 1.结构的级别和类一致,写在命名空间下面,可以定义字段.属性.方法.构造方法也可以通过关键字new创建对象. 2.结构中的字段不能赋初始值. 3.无参数的构造函数无论如何C#编译器 ...
- Android数据存储技术
Android提供了4种数据存储技术,分别是SharedPreferences.Files.SQLite数据库和网络存储数据.(有的开发者认为使用ContentProvider也可以算是一种,但我觉得 ...
- SQL Server调优系列基础篇 - 并行运算总结(二)
前言 上一篇文章我们介绍了查看查询计划的并行运行方式. 本篇我们接着分析SQL Server的并行运算. 闲言少叙,直接进入本篇的正题. 技术准备 同前几篇一样,基于SQL Server2008R2版 ...
- linux下神奇的script命令
script 是一个神奇命令,script 能够将终端的会话过程录制下来,然后使用 scriptreplay 就可以将其录制的结果播放给他人观看.script 的好处就在于你在终端中的所有操作.敲过的 ...
- ArcGIS Runtime SDK for WPF已不更新,后续将被ArcGIS Runtime SDK for .NET取代
ArcGIS Runtime SDK 10.2.5 for WPF is now available! by mbranscomb and Rex Hansen on January 27, 2015 ...
- Java实战之01Struts2-01简介及环境搭建
一.Struts2简介 1.Struts2概述 Struts2是Apache发行的MVC开源框架.注意:它只是表现层(MVC)框架. 2.Struts2的来历 Struts1:也是apache开发的一 ...
- 滑动条 Trackbar[OpenCV 笔记9]
OpenCV中没有实现按钮的功能,我们可以利用滑动条来实现按钮功能. , ); trackbarname 轨迹条的名字. winname 窗口的名字,轨迹条会依附在这个窗口上. value 一个指向整 ...
- bzoj1478:Sgu282 Isomorphism
思路:由于题目中是通过改变点的编号来判断两种染色方案是否相同,而染色的确是边,于是考虑如何将点置换转化为边置换. 对于一个有n个点的完全图,其点置换有n!个(即全排列个数),又由于每一个边置换都对应了 ...