Android Okhttp缓存:精细化每一个Request的CacheControl缓存控制策略(二)

客官°小女子只卖身不卖艺 2024-02-18 16:01 141阅读 0赞

Android Okhttp缓存:精细化每一个Request的CacheControl缓存控制策略(二)

之前我写的附录文章1,只是简单的使用缺省的方法实现Okhttp的缓存。现在使用CacheControl,精细化到每一个Request的缓存控制策略。
改造附录1代码:

  1. package zhangphil.app;
  2. import android.graphics.Bitmap;
  3. import android.graphics.BitmapFactory;
  4. import android.os.Bundle;
  5. import android.support.annotation.Nullable;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.widget.ImageView;
  8. import java.io.File;
  9. import java.io.IOException;
  10. import java.util.concurrent.TimeUnit;
  11. import okhttp3.Cache;
  12. import okhttp3.CacheControl;
  13. import okhttp3.Call;
  14. import okhttp3.Callback;
  15. import okhttp3.OkHttpClient;
  16. import okhttp3.Request;
  17. import okhttp3.Response;
  18. public class MainActivity extends AppCompatActivity {
  19. private OkHttpClient mOkHttpClient;
  20. @Override
  21. public void onCreate(@Nullable Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.activity_main);
  24. final ImageView image = (ImageView) findViewById(R.id.image);
  25. File cacheDir = new File(this.getCacheDir(), "zhangphilcache");
  26. Cache mCache = new Cache(cacheDir, 8 * 1024 * 1024); //8M缓存空间
  27. OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
  28. mOkHttpClient = mBuilder
  29. .connectTimeout(10, TimeUnit.SECONDS) //连接超时阈值
  30. .writeTimeout(10, TimeUnit.SECONDS) //写超时阈值
  31. .readTimeout(10, TimeUnit.SECONDS) //读超时阈值
  32. .retryOnConnectionFailure(true) //当失败后重试
  33. .cache(mCache)
  34. .build();
  35. String url = "https://www.baidu.com/img/bd_logo1.png";
  36. CacheControl mCacheControl = new CacheControl.Builder()
  37. .noTransform()
  38. .maxAge(60 * 60, TimeUnit.SECONDS) //缓存有效期时长
  39. .build();
  40. Request mRequest = new Request.Builder()
  41. .url(url)
  42. .cacheControl(mCacheControl)
  43. .build();
  44. mOkHttpClient.newCall(mRequest).enqueue(new Callback() {
  45. @Override
  46. public void onFailure(Call call, IOException e) {
  47. }
  48. @Override
  49. public void onResponse(Call call, Response response) throws IOException {
  50. if (response.isSuccessful()) {
  51. byte[] bytes = response.body().bytes();
  52. final Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  53. runOnUiThread(new Runnable() {
  54. @Override
  55. public void run() {
  56. image.setImageBitmap(bmp);
  57. }
  58. });
  59. }
  60. }
  61. });
  62. }
  63. @Override
  64. protected void onDestroy() {
  65. super.onDestroy();
  66. //取消所有Okhttp的网络请求
  67. mOkHttpClient.dispatcher().cancelAll();
  68. }
  69. }

maxAge 缓存有效期,Okhttp源代码中maxAge的实现:

  1. /**
  2. * Sets the maximum age of a cached response. If the cache response's age exceeds {@code
  3. * maxAge}, it will not be used and a network request will be made.
  4. *
  5. * @param maxAge a non-negative integer. This is stored and transmitted with {@link
  6. * TimeUnit#SECONDS} precision; finer precision will be lost.
  7. */
  8. public Builder maxAge(int maxAge, TimeUnit timeUnit) {
  9. if (maxAge < 0) throw new IllegalArgumentException("maxAge < 0: " + maxAge);
  10. long maxAgeSecondsLong = timeUnit.toSeconds(maxAge);
  11. this.maxAgeSeconds = maxAgeSecondsLong > Integer.MAX_VALUE
  12. ? Integer.MAX_VALUE
  13. : (int) maxAgeSecondsLong;
  14. return this;
  15. }

CacheControl.Builder在build时候的常用方法:
noCache 不使用缓存。
noStore 不要把网络数据缓存。
noTransform 不要转码。

Okhttp定义了若干常量缓存模型:
CacheControl.FORCE_NETWORK 强制使用网络数据。
CacheControl.FORCE_CACHE 强制使用缓存。

注意看Okhttp源码实现,在Okhttp源代码文件CacheControl.java中,CacheControl.FORCE_NETWORK的代码实现:

  1. public static final CacheControl FORCE_NETWORK = new Builder().noCache().build();

CacheControl.FORCE_CACHE的代码实现:

  1. /**
  2. * Cache control request directives that uses the cache only, even if the cached response is
  3. * stale. If the response isn't available in the cache or requires server validation, the call
  4. * will fail with a {@code 504 Unsatisfiable Request}.
  5. */
  6. public static final CacheControl FORCE_CACHE = new Builder()
  7. .onlyIfCached()
  8. .maxStale(Integer.MAX_VALUE, TimeUnit.SECONDS)
  9. .build();

附录:
1,《Android Okhttp缓存:Cache,创建OkHttpClient实现(一)》链接:http://blog.csdn.net/zhangphil/article/details/78326497

发表评论

表情:
评论列表 (有 0 条评论,141人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android Glide缓存策略

    一、glide缓存策略 缓存在请求网络图片时能减少不必要的流量浪费。Glide 缓存分为内存缓存和硬盘缓存,这两个缓存模块的作用各不相同,内存缓存的主要作用是 防止应用重

    相关 Okhttp 之HTTP 缓存实现

    以前学习 `HTTP` 的时候呢,都是从书本中学习概念,但是从来没有在服务器端和客户端去实践过。 作为移动开发人员呢,我觉得还是有必要了解`HTTP`在客户端的实现。这篇文章讲