HTTP 缓存

Redundant Downloads are Redundant

  The most fundamental way to reduce your downloads is to download only what you need. In terms of data, that means implementing REST APIs that allow you to specify query criteria that limit the returned data by using parameters such as the time of your last update.

  Similarly, when downloading images, it's good practice to reduce the size of the images server-side, rather than downloading full-sized images that are reduced on the client.

2.Cache Files Locally

  Another important technique is to avoid downloading duplicate data. You can do this by aggressive caching. Always cache static resources, including on-demand downloads such as full size images, for as long as reasonably possible. On-demand resources should be stored separately to enable you to regularly flush your on-demand cache to manage its size.

  To ensure that your caching doesn't result in your app displaying stale data, be sure to extract the time at which the requested content was last updated, and when it expires, from within the HTTP response headers. This will allow you to determine when the associated content should be refreshed.

复制代码
 1 long currentTime = System.currentTimeMillis());
 2 
 3 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 4 
 5 long expires = conn.getHeaderFieldDate("Expires", currentTime);
 6 long lastModified = conn.getHeaderFieldDate("Last-Modified", currentTime);
 7 
 8 setDataExpirationDate(expires);
 9 
10 if (lastModified < lastUpdateTime) {
11   // Skip update
12 } else {
13   // Parse update
14 }
复制代码

  Using this approach, you can also effectively cache dynamic content while ensuring it doesn't result in your application displaying stale information.

  You can cache non-sensitive data can in the unmanaged external cache directory:

Context.getExternalCacheDir();

  Alternatively, you can use the managed / secure application cache. Note that this internal cache may be flushed when the system is running low on available storage.

Context.getCacheDir();

  Files stored in either cache location will be erased when the application is uninstalled.

3.Use the HttpURLConnection Response Cache

  Android 4.0 added a response cache to HttpURLConnection. You can enable HTTP response caching on supported devices using reflection as follows:

复制代码
 1 private void enableHttpResponseCache() {
 2   try {
 3     long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
 4     File httpCacheDir = new File(getCacheDir(), "http");
 5     Class.forName("android.net.http.HttpResponseCache")
 6          .getMethod("install", File.class, long.class)
 7          .invoke(null, httpCacheDir, httpCacheSize);
 8   } catch (Exception httpResponseCacheNotAvailable) {
 9     Log.d(TAG, "HTTP response cache is unavailable.");
10   }
11 }
复制代码

  This sample code will turn on the response cache on Android 4.0+ devices without affecting earlier releases.

  With the cache installed, fully cached HTTP requests can be served directly from local storage, eliminating the need to open a network connection. Conditionally cached responses can validate their freshness from the server, eliminating the bandwidth cost associated with the download.

  Uncached responses get stored in the response cache for for future requests.

 

 

 

posted @   f9q  阅读(260)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示