Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 改装2-如何设置不同端点的动态缓存时间_Android_Retrofit_Retrofit2 - Fatal编程技术网

Android 改装2-如何设置不同端点的动态缓存时间

Android 改装2-如何设置不同端点的动态缓存时间,android,retrofit,retrofit2,Android,Retrofit,Retrofit2,我需要为不同的端点设置不同的缓存时间,这方面的最佳实践是什么 这是我的改装界面: public interface ServerApi { @GET("a1")// need to get 10 mintuns cache time Observable<A1> getA1(); @GET("a2")// need to get 20 mintuns cache time Observable<A2> getA2(); @GET("a3")// need to ge

我需要为不同的端点设置不同的缓存时间,这方面的最佳实践是什么

这是我的改装界面:

public interface ServerApi {

@GET("a1")// need to get 10 mintuns cache time
Observable<A1> getA1();

@GET("a2")// need to get 20 mintuns cache time
Observable<A2> getA2();

@GET("a3")// need to get 30 mintuns cache time
Observable<A3> getA3();

如果您的服务器提供了正确的缓存控制头。OkHttp将为您处理缓存

改造客户端的初始化缓存

int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(app.getCacheDir(), cacheSize);
构建OkHttp客户端,提供缓存

OkHttpClient client = new OkHttpClient.Builder()
            // Add cache
            .cache(cache)
            .build();
建筑改造

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory
                    .createWithScheduler(Schedulers.newThread()))
            // Add OkHttp client
            .client(client)
            .build();
如果由于某种原因,您的服务器不提供缓存头。您始终可以硬编码请求拦截器,并在客户端添加缓存头

您可能会使用以下几种组合:

Cache-Control: max-age=<seconds>
Cache-Control: max-stale[=<seconds>]
缓存控制:最大年龄=
缓存控制:最大过时[=]
但是如果你决定这么做,问一个简单的问题。如果我决定更改过期时间怎么办?您可能最终会编写一些不必要的代码或发布一个新的APK版本。不酷


祝你好运。

不是我的服务器,所以我无法控制缓存控制。要做硬代码,我需要把它写在接口上?有注释头吗@标题(“缓存控制:max age=640000”)这取决于具体情况。为了请求特定的缓存行为,您可以在请求中发送缓存控制头,但是您需要自己测试它,看看服务器是否使用缓存控制头进行响应。如果没有,您需要编写响应拦截器,以截获响应并附加正确的头。您解决了这个问题吗?@aleksandrbel检查Andrej Jurkin的答案,是否有效
Cache-Control: max-age=<seconds>
Cache-Control: max-stale[=<seconds>]