Caching Error With Retrofit 2 And Okhttp 3
I'm trying to cache HTTP responses from my company API but it looks like the app cannot access the cache directory: W/System.err: remove failed: ENOENT (No such file or directory)
Solution 1:
Regarding the first error, let's see the cache directory provided for OkHttpClient:
private static OkHttpClient provideOkHttpClient () {
return new OkHttpClient.Builder()
.addInterceptor(provideHttpLoggingInterceptor())
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache())
.build();
}
You have used the same cache directory for many OkHttpClient, many instances may stomp on each other, corrupt the response cache. To fix this, you can use exactly once OkHttpClient, configure it with their cache, and use that same instance everywhere. You can try as below:
privatestatic Retrofit provideRetrofit(String baseUrl) {
returnnewRetrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
privatestaticOkHttpClientokHttpClient=newOkHttpClient.Builder()
.addInterceptor(provideHttpLoggingInterceptor())
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache())
.build();
For more info about cache with OkHttpClient, you can take a look at this link.
Solution 2:
You might be missing the INTERNET permission in the manifest.
<uses-permission android:name="android.permission.INTERNET" />
That's a common reason for getting UnknownHostException
errors.
Alternatively, make sure you can actually reach the site in question on that device by visiting the site in a browser.
Post a Comment for "Caching Error With Retrofit 2 And Okhttp 3"