Android okhttp获取缓存响应

时间:2015-03-22 13:32:38

标签: android caching okhttp

我不是专家处理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);
}

}

我的缓存正在填充,因此当没有可用连接时,它应该从缓存中读取。 cache files

来自服务器的响应标头:

  • 连接:关闭
  • 内容类型:应用/ JSON;字符集= ISO-8859-1
  • 日期:星期一,2015年3月23日11:04:44 GMT
  • 服务器:Apache
  • 传输编码:分块
  • X-Powered-By:Servlet / 2.5 JSP / 2.1

请求标题:

  • 接受:text / html的,应用/ XHTML + xml的,应用/ XML; Q = 0.9,图像/ WEBP, / 的; Q = 0.8
  • 接受编码:gzip,deflate,sdch
  • 接受语言:PT-PT,PT; Q = 0.8,的en-US; Q = 0.6,连接; Q = 0.4,FR; Q = 0.2
  • 缓存控制:最大年龄= 0
  • 连接:保活
  • 主机:cantShare:448
  • User-Agent:Mozilla / 5.0(Windows NT 6.3; WOW64)AppleWebKit / 537.36 (KHTML,与Gecko一样)Chrome / 41.0.2272.101 Safari / 537.36

1 个答案:

答案 0 :(得分:1)

当你收到回复时,你需要完全阅读它,否则它不会被缓存。这是因为当你读完它的主体时,OkHttp只会将响应提交给缓存。

您不需要504的特殊情况。只需定期发出请求,如果可以,它将使用缓存。