栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java可以在脱机时使用OKHttp进行改造以使用缓存数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java可以在脱机时使用OKHttp进行改造以使用缓存数据

编辑改造2.x:

OkHttp Interceptor
是脱机时访问缓存的正确方法:

1)创建拦截器:

private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {    @Override public Response intercept(Chain chain) throws IOException {        Response originalResponse = chain.proceed(chain.request());        if (Utils.isNetworkAvailable(context)) { int maxAge = 60; // read from cache for 1 minute return originalResponse.newBuilder()         .header("Cache-Control", "public, max-age=" + maxAge)         .build();        } else { int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale return originalResponse.newBuilder()         .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)         .build();        }    }

2)安装客户端:

OkHttpClient client = new OkHttpClient();client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);//setup cacheFile httpCacheDirectory = new File(context.getCacheDir(), "responses");int cacheSize = 10 * 1024 * 1024; // 10 MiBCache cache = new Cache(httpCacheDirectory, cacheSize);//add cache to the clientclient.setCache(cache);

3)将客户添加到改造中

Retrofit retrofit = new Retrofit.Builder()        .baseUrl(base_URL)        .client(client)        .addConverterFactory(GsonConverterFactory.create())        .build();

另请检查@kosiara-Bartosz Kosarzycki的答案。您可能需要从响应中删除一些标头。

OKHttp 2.0.x(检查原始答案):
由于OKHttp 2.0.x HttpResponseCache是Cache,所以setResponseCache是setCache。因此,您应该setCache这样:

        File httpCacheDirectory = new File(context.getCacheDir(), "responses");        Cache cache = null;        try { cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);        } catch (IOException e) { Log.e("OKHttp", "Could not create http cache", e);        }        OkHttpClient okHttpClient = new OkHttpClient();        if (cache != null) { okHttpClient.setCache(cache);        }        String hostURL = context.getString(R.string.host_url);        api = new RestAdapter.Builder()     .setEndpoint(hostURL)     .setClient(new OkClient(okHttpClient))     .setRequestInterceptor()     .build()     .create(MyApi.class);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/398600.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号