public static OkHttpClient genericClient() {
if (client != null) {
return client;
}
//缓存路径
File cacheFile = new File(App.getContext().getCacheDir(), "HttpCache");
Cache cache = new Cache(cacheFile, 1024 * 1024 * 10);//缓存文件为10MB
Interceptor interceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
int maxAge = 60 * 60; // 有网络时 设置缓存超时时间1个小时
int maxStale = 60 * 60 * 24 * 28; // 无网络时,设置超时为4周
Request request = chain.request();
if (isNetworkReachable(App.getContext())) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_NETWORK)//有网络时只从网络获取
.build();
} else {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)//无网络时只从缓存中读取
.build();
}
okhttp3.Response response = chain.proceed(request);
if (isNetworkReachable(App.getContext())) {
response = response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
response = response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return response;
}
};
client = new OkHttpClient.Builder()
.addNetworkInterceptor(interceptor)
.connectTimeout(10 * 1000, TimeUnit.SECONDS)
.cache(cache)
.build();
return client;
}
网络判断 需添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public static Boolean isNetworkReachable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo current = cm.getActiveNetworkInfo();
if (current == null) {
return false;
}
return (current.isAvailable());
}
Get请求可将其缓存,JSONConverterFactory是自定义的转换
Retrofit.Builder builder = new Retrofit.Builder()
.client(genericClient())
.baseUrl(baseUrl)
.addConverterFactory(new JSONConverterFactory());