java http查询参数进行缓存,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 cache

File httpCacheDirectory = new File(context.getCacheDir(), "responses");

int cacheSize = 10 * 1024 * 1024; // 10 MiB

Cache cache = new Cache(httpCacheDirectory, cacheSize);

//add cache to the client

client.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(/*rest of the answer here */)

.build()

.create(MyApi.class);

2020-03-08

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值