OKHTTP - 设置缓存后如何缓存某些改进的 http 响应

OKHTTP - After setting cache how to cache certain retrofit http responses

为了在 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 的目录。我现在如何缓存某个响应?我不想只缓存选定的所有改造响应?

只是想让你知道这个答案使用的是 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 headers。 像

public interface GitHubService {

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

}