【问题标题】:Cache Specific responses using retrofit使用改造缓存特定响应
【发布时间】:2018-01-18 12:02:18
【问题描述】:

我正在使用 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();
     }
 }

它工作正常,但我想知道实现我想要的最佳方法。还有另一种方法来识别我的请求并区分它们而不是标题。

【问题讨论】:

    标签: android caching retrofit2 okhttp


    【解决方案1】:

    最后,感谢andre tietz,他通过对请求的自定义注释提出了另一个解决方案。

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 2017-04-29
      相关资源
      最近更新 更多