我想知道是否有一种方法可以在改造中自定义特定请求,而其余的仍然是不可缓存的。可能使用自定义注释:
@Cacheable
@GET("/user")
Call<UserResponse> getUser(@Path("id") String id);
有谁知道怎么做?
答案 0 :(得分:0)
您可以针对缓存请求和非缓存请求进行初始化改造,如下所示
用于缓存
public static Retrofit initializeRetrofit(Context mContext) {
OkHttpClient client = new OkHttpClient();
final File baseDir = mContext.getCacheDir();
if (baseDir != null) {
final File cacheDir = new File(baseDir, "HttpResponseCache");
client.setCache(new Cache(cacheDir, 10 * 1024 * 1024));
}
//Setting time out for okHTTP
client.setConnectTimeout(60, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(60, TimeUnit.SECONDS);
client.setRetryOnConnectionFailure(true);
/**
* For Logging in retrofit
*/
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.interceptors().add(interceptor);
return new Retrofit.Builder()
.baseUrl(Constants.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
非缓存
public static Retrofit initializeRetrofitWithoutCache(Context mContext) {
OkHttpClient client = new OkHttpClient();
//Setting time out for okHTTP
client.setConnectTimeout(60, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(60, TimeUnit.SECONDS);
client.setRetryOnConnectionFailure(true);
/**
* For Logging in retrofit
*/
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.interceptors().add(interceptor);
return new Retrofit.Builder()
.baseUrl(Constants.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
在进行网络通话之前使用这些功能初始化改造,在api通话功能中使用这些功能
你可以做这样的事情来调用你的改装
使用缓存进行呼叫
Call<ResponseBody> call = initializeRetrofit()
.create(RetrofitInterface.class)
.yourFunction(params...);
对于没有缓存的呼叫
Call<ResponseBody> call = initializeRetrofitWithoutCache()
.create(RetrofitInterface.class)
.yourFunction(params...);
您还可以在其上构建一个包装器,您可以在其中定义路由,并使用标志来检查是否需要缓存