只是为了让您知道此答案使用的是 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);
}