Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data on OkHttp response code 304?

I read that a response with code 304 (Not Modified) should have no body. In that case, does OkHttp get the body from the cache, or shall we get it explicitely, i.e.

if reponseCode == 304:
      body = <getDataFromCache>

In the latter case, how to get the data from the cache?

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?
like image 277
jul Avatar asked Mar 16 '26 10:03

jul


1 Answers

OkHttp will return data from its response cache.

like image 164
Jesse Wilson Avatar answered Mar 19 '26 00:03

Jesse Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!