android post 缓存,android - Cache POST requests with OkHttp - Stack Overflow

I make some POST requests to my server with OkHttp. This works fine.

Now I want use the cache of OkHttp to cache the responses of the requests and use them when the device is offline.

I tried many solutions from other questions, but none of them work.

I use OkHttp 2.5.0

With the code below, I get a valid response, when the device has internet access.

But if I turn the internet off, it throws a java.net.UnknownHostException: Unable to resolve host "example.com": No address associated with hostname

Here is my current code, which does not work:

Interceptor for rewriting the cache headers:

private final Interceptor mCacheControlInterceptor = new Interceptor() {

@Override

public Response intercept(Chain chain) throws IOException {

Request request = chain.request();

if (isOnline()) {

request.newBuilder()

.header("Cache-Control", "public, only-if-cached, max-stale=7887")

.build();

} else {

request.newBuilder()

.header("Cache-Control", "public, max-stale=2419200")

.build();

}

Response response = chain.proceed(request);

// Re-write response CC header to force use of cache

return response.newBuilder()

.header("Cache-Control", "public, max-age=86400") // 1 day

.build();

}

};

Method to get the client:

private OkHttpClient getHttpClient() {

if (mHttpClient == null) {

mHttpClient = new OkHttpClient();

mHttpClient.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS);

File cacheDir = mContext.getDir(CACHE_NAME, Context.MODE_PRIVATE);

mHttpClient.setCache(new Cache(cacheDir, CACHE_SIZE));

mHttpClient.networkInterceptors().add(mCacheControlInterceptor);

}

return mHttpClient;

}

Make the request:

RequestBody body = RequestBody.create(TEXT, data);

Request request = new Request.Builder()

.url(url)

.post(body)

.build();

Response response = getHttpClient().newCall(request).execute();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值