本文介绍了检测OkHttp响应是否来自缓存(具有翻新功能)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有办法检测改造响应是否来自已配置的OkHttp缓存或实时响应?

Is there a way to detect if a Retrofit response comes from the configured OkHttp cache or is a live response?

客户定义:

Cache cache = new Cache(getCacheDirectory(context), 1024 * 1024 * 10);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cache(cache)
            .build();

Api定义:

@GET("/object")
Observable<Result<SomeObject>> getSomeObject();

示例调用:

RetroApi retroApi = new Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(baseUrl)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(RetroApi.class);

result = retroApi.getSomeObject().subscribe((Result<SomeObject> someObjectResult) -> {
     isFromCache(someObjectResult); // ???
});

推荐答案

任何时候只要您有 okhttp3.Response (retrofit2.Response.raw()),您可以检查响应是否来自缓存.

Any time you have an okhttp3.Response (retrofit2.Response.raw()), you can check if the response is from the cache.

引用杰西·威尔逊的话:

To quote Jesse Wilson:

.networkResponse() –您的请求仅通过网络提供.

.networkResponse() only – your request was served from network exclusively.

.cacheResponse() –您的请求是专门从缓存中提供的.

.cacheResponse() only – your request was served from cache exclusively.

.networkResponse()和.cacheResponse()–您的请求是有条件的GET,因此标头来自网络,正文来自缓存.

.networkResponse() and .cacheResponse() – your request was a conditional GET, so headers are from the network and body is from the cache.

因此,在您的示例中,isFromCache方法如下所示:

So for your example, the isFromCache method would look like:

boolean isFromCache(Result<?> result) {
  return result.response().raw().networkResponse() == null;
}

这篇关于检测OkHttp响应是否来自缓存(具有翻新功能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:36