我正在使用retrofit2来使用缓存拦截器来兑现响应,但我想缓存特定请求而不是所有请求,所以我执行以下操作。 我将我的api定义为:
public interface ExampleApi {
@GET("home/false")
@Headers("MyCacheControl: public, max-age=60000")
Observable<ExampleModel> getDataWithCache();
@GET("hello")
@Headers("MyCacheControl: no-cache")
Observable<ExampleModel> getDataWithoutCache();
}
然后我的拦截器是:
public class OfflineResponseInterceptor implements Interceptor {
// tolerate 4-weeks stale
private static final int MAX_STALE = 60 * 60 * 24 * 28;
private final Context context;
public OfflineResponseInterceptor(Context context) {
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetworkUtil.isConnected(context)) {
request = request.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + MAX_STALE)
.build();
}
return chain.proceed(request);
}
}
和
public class OnlineResponseInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String cacheControl = request.header("MyCacheControl");
Logger.debug("okhttp MyCacheControl ", cacheControl + " ");
okhttp3.Response originalResponse = chain.proceed(request);
return originalResponse.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", cacheControl)
.build();
}
}
它工作正常但我想知道实现我想要的最佳方式。还有另一种方法来识别我的请求并区分它们而不是标题。