Android 带改装2缓存控制的脱机模式
我正在开发一个android应用程序,它需要离线模式,我正在使用带有缓存控制的翻新2,但面临的问题是缓存文件没有被创建,并且该文件夹中只有名为journal的文件被创建。我在这里发布我的ApiClient.java文件代码Android 带改装2缓存控制的脱机模式,android,retrofit2,cache-control,offline-caching,Android,Retrofit2,Cache Control,Offline Caching,我正在开发一个android应用程序,它需要离线模式,我正在使用带有缓存控制的翻新2,但面临的问题是缓存文件没有被创建,并且该文件夹中只有名为journal的文件被创建。我在这里发布我的ApiClient.java文件代码 public class ApiClient { public static final String BASE_URL = "http://www.something.com/"; private static Retrofit retrofit = null; priv
public class ApiClient {
public static final String BASE_URL = "http://www.something.com/";
private static Retrofit retrofit = null;
private static APIInterfaces apiInterface;
private static Context mcontext=getApplicationContext();
static Interceptor OFFLINE_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!isConnected()) {
int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
request = request.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return chain.proceed(request);
}
};
static Interceptor ONLINE_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response response = chain.proceed(chain.request());
int maxAge = 60; // read from cache
return response.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
}
};
protected static Retrofit getClient() {
if (retrofit == null) {
createFolder();
Gson gson = new GsonBuilder()
.setLenient()
.create();
OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.cache(new Cache(new File(Environment.getExternalStorageDirectory() + File.separator + "something"), 10 * 1024 * 1024)) // 10 MB
.addInterceptor(OFFLINE_INTERCEPTOR)
.addNetworkInterceptor(ONLINE_INTERCEPTOR)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL).client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
public static APIInterfaces getApiInterface() {
if (apiInterface == null)
apiInterface = ApiClient.getClient().create(APIInterfaces.class);
return apiInterface;
}
private static boolean isConnected() {
try {
android.net.ConnectivityManager e = (android.net.ConnectivityManager) mcontext.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = e.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {
Log.w(TAG, e.toString());
}
return false;
}
public static boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (mcontext.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions((Activity) mcontext,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
return true;
}
}
private static void createFolder() {
if (isStoragePermissionGranted()) {
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "Something");
if (!folder.exists()) {
folder.mkdir();
}
}
}
公共类ApiClient{
公共静态最终字符串BASE_URL=”http://www.something.com/";
私人静态改装=空;
专用静态接口;
私有静态上下文mcontext=getApplicationContext();
静态拦截器脱机\u拦截器=新拦截器(){
@凌驾
公共okhttp3.响应截获(链)引发IOException{
Request=chain.Request();
如果(!isConnected()){
int maxStale=60*60*24*28;//容忍4周的过期
request=request.newBuilder()
.header(“缓存控制”、“公共,仅当缓存时,max stale=“+maxStale”)
.build();
}
返回链。继续(请求);
}
};
静态拦截器联机\u拦截器=新拦截器(){
@凌驾
公共okhttp3.响应截获(链)引发IOException{
okhttp3.Response-Response=chain.procedure(chain.request());
int maxAge=60;//从缓存读取
返回响应。newBuilder()
.header(“缓存控制”、“公共、最大年龄=“+maxAge”)
.build();
}
};
受保护的静态改装getClient(){
如果(改装==null){
createFolder();
Gson Gson=new GsonBuilder()
.setLenient()
.create();
OkHttpClient OkHttpClient=新的OkHttpClient
.Builder()
.cache(新缓存(新文件(Environment.getExternalStorageDirectory()+File.separator+“某物”),10*1024*1024))//10 MB
.addInterceptor(脱机_侦听器)
.addNetworkInterceptor(在线截取器)
.build();
改装=新改装.Builder()
.baseUrl(基本URL).client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
回流改造;
}
公共静态API接口getAPI接口(){
if(apinterface==null)
apiInterface=ApiClient.getClient().create(APIInterfaces.class);
返回接口;
}
私有静态布尔值未连接(){
试一试{
android.net.ConnectivityManager e=(android.net.ConnectivityManager)mcontext.getSystemService(
连接(U服务);
NetworkInfo activeNetwork=e.getActiveNetworkInfo();
返回activeNetwork!=null&&activeNetwork.isConnectedOrConnecting();
}捕获(例外e){
Log.w(TAG,e.toString());
}
返回false;
}
公共静态布尔值IsStorage PermissionGrated(){
如果(Build.VERSION.SDK_INT>=23){
if(mcontext.checkSelfPermission(android.Manifest.permission.WRITE\u外部存储)
==PackageManager.权限(已授予){
返回true;
}否则{
ActivityCompat.requestPermissions((活动)mcontext,
新字符串[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
返回false;
}
}
否则{//当您使用拦截器更改标头时,会自动授予sdk上的权限,在调用CacheStrategy.isCacheable()
之前,不会进行任何调整
尝试使用networkInterceptors()
调用更改interceptors()
请看这里:
此外,您不能使用OkHttp的缓存缓存POST请求。您需要使用其他机制存储它们
其他机制:
有几种方法,一种是将在线结果存储到本地数据库中,然后在离线时从那里检索,大多数人都是这样做的,第二种方法是覆盖OKHTTP
,但这对移动设备来说,性能比效益更昂贵,第三种方法显然是将POST API结构转换为GET
但是,请看一看,它也包含一篇博客文章,这将对您有所帮助。检查:您是否尝试脱机加载数据?是成功还是失败?@sreehari缓存文件未被创建。在这种情况下,如何脱机加载数据…没有数据files@TejashwiKalpTaru谢谢你的回答,但我想知道具体问题是什么我的代码…你是否尝试过networkInterceptors()
而不是interceptors()
看看这里,非常感谢你帮了我一天的忙…问题是“无法使用OkHttp的缓存缓存POST请求”@PoonamParth欢迎:)现在我遇到了使用哪种机制进行请求后缓存的问题…请阅读一些建议将请求后转换为请求后的堆栈,但我认为有一个更好的答案……您能提出一些建议吗?@PoonamParth使用本地数据库缓存