我不是专家处理http,但是想要完成的是:
如果响应在缓存返回缓存中,如果不能简单地返回网络响应。
但问题是响应代码总是504,但我确定它是缓存的,所以根据我的理解它应该返回!= 504,代码是在“doGetRequest”方法中。
我的okhttp客户端:
public class RestAsyncHttpClient {
/* Constants */
private static final String TAG = "RestAsyncHttpClient";
private static long HTTP_CACHE_SIZE = 10 * 1024 * 1024; // 10 MiB
private static final String DISK_CACHE_SUBDIR = "cacheApi";
/* Properties */
private static OkHttpClient mHttpClient;
private static Cache cache;
private static RestAsyncHttpClient instance = null;
private Context context;
public static RestAsyncHttpClient getInstance() {
if (instance == null) {
instance = new RestAsyncHttpClient();
}
return instance;
}
/**
* Initialize HttpClient
*/
public void initialize(Context context) {
setContext(context);
mHttpClient = new OkHttpClient();
configureSslSocketFactory();
configureCache();
configureTimeouts();
}
private void setContext(Context context) {
this.context = context;
}
private void configureSslSocketFactory() {
mHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
}
public static void doGetRequest(String url, Callback callback) throws IOException {
Request cachedRequest = new Request.Builder()
.cacheControl(new CacheControl.Builder().onlyIfCached().build())
.url(url)
.build();
Response forceCacheResponse = mHttpClient.newCall(cachedRequest).execute();
if (forceCacheResponse.code() != 504) {
// The resource was cached! Show it.
callback.onResponse(forceCacheResponse);
} else {
Request networkRequest = new Request.Builder().url(url).build();
mHttpClient.newCall(networkRequest).enqueue(callback);
}
}
private void configureCache() {
if (cache == null)
cache = createHttpClientCache(context);
mHttpClient.setCache(cache);
}
private static Cache createHttpClientCache(Context context) {
try {
File cacheDir = context.getDir("cache_api", Context.MODE_PRIVATE);
return new Cache(cacheDir, HTTP_CACHE_SIZE);
} catch (IOException exp) {
LogHelper.error(TAG, "Couldn't create http cache because of IO problem.", exp);
return null;
}
}
private void configureTimeouts() {
mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
mHttpClient.setWriteTimeout(35, TimeUnit.SECONDS);
mHttpClient.setReadTimeout(35, TimeUnit.SECONDS);
}
}
我的缓存正在填充,因此当没有可用连接时,它应该从缓存中读取。
来自服务器的响应标头:
请求标题:
答案 0 :(得分:1)
当你收到回复时,你需要完全阅读它,否则它不会被缓存。这是因为当你读完它的主体时,OkHttp只会将响应提交给缓存。
您不需要504的特殊情况。只需定期发出请求,如果可以,它将使用缓存。