【问题标题】:OKHTTP - After setting cache how to cache certain retrofit http responsesOKHTTP - 设置缓存后如何缓存某些改造 http 响应
【发布时间】:2016-03-20 14:40:09
【问题描述】:

要在 android okhttp 中缓存,我设置了以下代码:

final @Nullable File baseDir = context.getCacheDir();
if (baseDir != null) {
    final File cacheDir = new File(baseDir, "HttpResponseCache");
okHttpClient.setCache(new Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE));
}

这会将我的缓存设置为我称为 HttpResponseCache 的目录。我现在如何缓存某个响应?我不想只缓存选定的所有改造响应?

【问题讨论】:

    标签: android caching retrofit okhttp


    【解决方案1】:

    只是为了让您知道此答案使用的是 Retrofit 2 beta。就本答案而言,差别不大。

    我假设你有这样的东西来获得改造客户。

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(new ErrorHandlingCallbackAdapter.ErrorHandlingCallAdapterFactory());
    

    希望你也有这样的方法:

    public static <S> S createCachedService(Context context, Class<S> serviceClass) {
    
        Retrofit retrofit = builder.client(sOkHttpClient).build();
        return retrofit.create(serviceClass);
    }
    

    但是你应该有两种方法。一种添加 okhttp 客户端,一种不添加。

    public static <S> S createService(Context context, Class<S> serviceClass) {
    
        Retrofit retrofit = builder.build();
        return retrofit.create(serviceClass);
    }
    

    当您需要进行缓存调用时,只需使用缓存的服务创建者即可。

    据我了解,如果您希望对该端点的所有请求都跳过缓存,也可以向该端点添加 @Header 注释。 okhttp 应该尊重您的 Cache-Control 标头。 像

    public interface GitHubService {
    
        @Headers("Cache-Control: no-cache")
        @GET("/users/{user}/repos")
        Call<List<Repo>> listRepos(@Path("user") String user);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-21
      • 2017-02-03
      • 2018-05-16
      • 2018-06-19
      • 2016-12-06
      • 2023-04-10
      • 2016-08-03
      • 2011-03-25
      • 1970-01-01
      相关资源
      最近更新 更多