OKhttp的理解-CacheInterceptor

用法

  1. noCache

Request request = new Request.Builder()
        .cacheControl(new CacheControl.Builder().noCache().build())
        .url("http://publicobject.com/helloworld.txt")
        .build();
  1. maxAge

Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder().maxAge(0, TimeUnit.SECONDS).build())
    .url("http://publicobject.com/helloworld.txt")
    .build();
  1. Only-If-Cached

Request request = new Request.Builder()
      .cacheControl(new CacheControl.Builder()
      .onlyIfCached()
      .build())
      .url("http://publicobject.com/helloworld.txt")
      .build();
Response forceCacheResponse = client.newCall(request).execute();
if (forceCacheResponse.code() != 504) {
    // The resource was cached! Show it.
} else {
   // The resource was not cached.
}

4.MaxStale

Request request = new Request.Builder()
        .cacheControl(new CacheControl.Builder()
        .maxStale(365, TimeUnit.DAYS)
        .build())
        .url("http://publicobject.com/helloworld.txt")
        .build();

Cache设计

public final class Cache implements Closeable, Flushable {
    final InternalCache internalCache = new InternalCache() {
        @Override
        public @Nullable
        Response get(Request request) throws IOException {
            return Cache.this.get(request);
        }

        @Override
        public @Nullable
        CacheRequest put(Response response) throws IOException {
            return Cache.this.put(response);
        }

        @Override
        public void remove(Request request) throws IOException {
            Cache.this.remove(request);
        }

        @Override
        public void update(Response cached, Response network) {
            Cache.this.update(cached, network);
        }

        @Override
        public void trackConditionalCacheHit() {
            Cache.this.trackConditionalCacheHit();
        }

        @Override
        public void trackResponse(CacheStrategy cacheStrategy) {
            Cache.this.trackResponse(cacheStrategy);
        }
    };
    final DiskLruCache cache;

    public Cache(File directory, long maxSize) {
        this(directory, maxSize, FileSystem.SYSTEM);
    }

    Cache(File directory, long maxSize, FileSystem fileSystem) {
        this.cache = DiskLruCache.create(fileSystem, directory, VERSION, ENTRY_COUNT, maxSize);
    }
}

OKhttp的理解-CacheInterceptor

上一篇:angular国际化 / rxjs使用技巧


下一篇:keepalived实现LVS-DR模型的高可用