我正在从两台服务器请求json数据。 OkHttp不缓存来自第一台服务器的响应,来自第二台服务器的响应正在缓存。
来自第一台服务器的响应,缓存由于某种原因无效:
<--- HTTP 200
Cache-Control: public, max-age=2230
Content-Type: application/json; charset=utf-8
Expires: Sat, 28 Mar 2015 11:34:13 GMT
Last-Modified: Sat, 28 Mar 2015 10:34:13 GMT
Vary: *
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Date: Sat, 28 Mar 2015 10:57:01 GMT
Content-Length: 1381
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1427540192625
OkHttp-Received-Millis: 1427540192940
<--- END HTTP (1381-byte body)
设备离线时来自第一台服务器的响应:
---> HTTP GET
Cache-Control: public, only-if-cached, max-stale=2419200
---> END HTTP (no body)
<--- HTTP 504
<--- END HTTP (0-byte body)
来自第二台服务器的响应,缓存有效:
<--- HTTP 200
Content-Type: application/json; charset=utf-8
Date: Sat, 28 Mar 2015 11:19:51 GMT
Server: nginx/1.6.2
X-Berry-Env: p4
X-Berry-Version: 2.10.0.96e8b7c
X-Powered-By: Express
Connection: keep-alive
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1427541591103
OkHttp-Received-Millis: 1427541591385
<--- END HTTP (92663-byte body)
设备离线时来自第二台服务器的响应:
<--- HTTP 200
Content-Type: application/json; charset=utf-8
Date: Sat, 28 Mar 2015 11:19:51 GMT
Server: nginx/1.6.2
X-Berry-Env: p4
X-Berry-Version: 2.10.0.96e8b7c
X-Powered-By: Express
Connection: keep-alive
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1427541591103
OkHttp-Received-Millis: 1427541591385
Warning: 110 HttpURLConnection "Response is stale"
Validating map...
<--- END HTTP (92663-byte body)
我跟着this answer,这是我的休息适配器:
protected RestAdapter getRestAdapter(final Context context) {
if (restAdapter == null) {
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(context.getCacheDir(), cacheSize);
OkHttpClient client = new OkHttpClient();
client.setCache(cache);
restAdapter = new RestAdapter.Builder()
.setConverter(new GsonConverter(gson))
.setEndpoint(API_URL)
.setClient(new OkClient(client))
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
if (Utils.isOnline(context)) {
int maxAge = 60;
request.addHeader("Cache-Control", "public, max-age=" + maxAge);
} else {
int maxStale = 60 * 60 * 24 * 28;
request.addHeader("Cache-Control",
"public, only-if-cached, max-stale=" + maxStale);
}
}
})
.build();
restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);
}
return restAdapter;
}
答案 0 :(得分:1)
我通过使用网络拦截器解决了这个问题。
答案 1 :(得分:0)
除了Ivan的回答,OkHttp3缓存不适用于帖子请求。 要缓存帖子请求,您必须使用其他一些机制。