如何获取OkHttp响应代码304的数据?

时间:2014-10-02 12:03:26

标签: android caching okhttp

我读到代码为304(未修改)的响应应该没有正文。在那种情况下,OkHttp是从缓存中获取正文,还是我们明确地得到它,即

if reponseCode == 304:
      body = <getDataFromCache>

在后一种情况下,如何从缓存中获取数据?

OkHttpClient client = new OkHttpClient();

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

Cache cache = null;
try {
    cache = new Cache(cacheDirectory, 10 * 1024 * 1024); // 10M
    client.setCache(cache);
} catch (IOException e) {
    Log.e("AbstractFeedIntentService", "Could not create http cache", e);
}

Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url);
Request request = requestBuilder.build();

Call call = client.newCall(request);
Response response = call.execute();

// if code==304, does the response contain the data from the cache. If not, how to get it?

1 个答案:

答案 0 :(得分:2)

OkHttp将从其响应缓存中返回数据。