public void init(Context context) {
//指定缓存路径
String directoryPath = context.getCacheDir().getAbsolutePath() + "/responses";
File directory = new File(directoryPath);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(new Cache(directory, DEFAULT_CACHE_SIZE))//指定缓存目录和大小
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)//网络拦截器
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.HOST)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
mApi = retrofit.create(Api.class);
}
----------------------------------------------------------------------------------------------------------------
初始化
public class GooglePlayApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
NetworkManager.init(getApplicationContext());
}
}
-----------------------------------------------------------------
重写网络响应的Cache-Control
如果服务器在网络响应头里配置了Cache-Contorol,那么其实客户端是不需要做任何事情就能使用缓存的,但如果服务器没有配置,我们可以拦截这个网络响应,加入我们自己的配置。
/**
* Dangerous interceptor that rewrites the server's cache-control header.
*/
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
//设置5分钟后缓存过期
CacheControl.Builder builder = new CacheControl.Builder().maxAge(5, TimeUnit.MINUTES);
return originalResponse.newBuilder()
.header(CACHE_CONTROL, builder.build().toString())
.build();
}
};