Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Retrofit+Okhttp using httpCaching as a default in Android?

I use retrofit and okhttp in one of our applications.

I can't really find a good explanation for the default behaviour of Retrofit.

If Okhttp is on the class path it will be automatically used. But as far as I can see it the default HttpResponseCache is null.

Do I need to explicitly enable caching with Retrofit and Okhttp?

like image 953
Janusz Avatar asked Feb 05 '14 12:02

Janusz


People also ask

How do I use OkHttp with retrofit?

Solution 1: Sharing Default OkHttp Instance In order to make them share a single OkHttp instance, you can simply pass it explicitly on the builder: OkHttpClient okHttpClient = new OkHttpClient(); Retrofit retrofitApiV1 = new Retrofit. Builder() . baseUrl("https://futurestud.io/v1/") .

How does OkHttp cache work?

Basically: The client will send out something like timestamp or Etag of the last request. The server can then check if there is some data has changed in during that period of time or not. If nothing has changed, the server can just give a special code (304 -not modified) without sending the whole same response again.

Does Retrofit have cache?

Cache-control is a header used to specify caching policies in client requests and server responses. Note: You can only cache the GET requests.


3 Answers

Correct implementation for OkHttpClient v2:

int cacheSize = 10 * 1024 * 1024; // 10 MiB
File cacheDir = new File(context.getCacheDir(), "HttpCache");
Cache cache = new Cache(cacheDir, cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
    .cache(cache)
    .build();

see documentation

like image 178
e.shishkin Avatar answered Oct 15 '22 09:10

e.shishkin


DEPRECATED for OkHttpClient v2.0.0 and higher

As Jesse Wilson pointed out you need to create your own cache.
The following code should create a 10MB cache.

File httpCacheDirectory = new File(application.getApplicationContext()
    .getCacheDir().getAbsolutePath(), "HttpCache");

HttpResponseCache httpResponseCache = null;
try {
   httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024);
} catch (IOException e) {
   Log.e(getClass().getSimpleName(), "Could not create http cache", e);
}

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setResponseCache(httpResponseCache);
builder.setClient(new OkClient(okHttpClient));

The code is based on Jesse Wilsons example on Github.

like image 36
Janusz Avatar answered Oct 15 '22 08:10

Janusz


You should manually create your OkHttpClient and configure it how you like. In this case you should install a cache. Once you have that create an OkClient and pass it to Retrofit's RestAdapter.Builder

Also, no caching for HTTP POST requests. GETs will be cached, however.

like image 30
Jesse Wilson Avatar answered Oct 15 '22 10:10

Jesse Wilson