Sto utilizzando il retrofit 2 e OkHttp3 per richiedere dati dal server. Ho appena aggiunto un codice cache offline ma non funziona come previsto. Ho ricevuto l'errore "Impossibile risolvere l'host" <> ": nessun indirizzo associato al nome host".Trovato questo errore con retrofit2 e OkHttp3. Impossibile risolvere l'host "<host-name>": Nessun indirizzo associato al nome host
Ciò si verifica quando si tenta di recuperare i dati dalla cache (in assenza di connessione Internet). Un frammento di codice è sotto.
public static Interceptor provideCacheInterceptor() {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
// re-write response header to force use of cache
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(2, TimeUnit.MINUTES)
.build();
return response.newBuilder()
.header(CACHE_CONTROL, cacheControl.toString())
.build();
}
};
}
public static Interceptor provideOfflineCacheInterceptor() {
return new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!hasNetwork) {
CacheControl cacheControl = new CacheControl.Builder()
.onlyIfCached()
.maxStale(7, TimeUnit.DAYS)
.build();
request = request.newBuilder()
.removeHeader("Pragma")
.cacheControl(cacheControl)
.build();
}
return chain.proceed(request);
}
};
}
private static Cache provideCache() {
Cache cache = null;
try {
cache = new Cache(new File(AdeptAndroid.getInstance().getCacheDir(), "http-cache"),
10 * 1024 * 1024); // 10 MB
} catch (Exception e) {
Log.d("Test", "Could not create Cache!");
}
return cache;
}
E infine un metodo che combina tutti questi è qui.
private static OkHttpClient provideOkHttpClient() {
return new OkHttpClient.Builder()
.addInterceptor(provideHttpLoggingInterceptor())
.addInterceptor(provideOfflineCacheInterceptor())
.addNetworkInterceptor(provideCacheInterceptor())
.cache(provideCache())
.build();
}
L'intestazione dell'impostazione in questo modo (esattamente 50000) ha risolto il problema. .header ("Cache-Control", String.format ("max-age =% d", 50000)) –
@WaqarYounis Grazie per la risposta, ma non funziona neanche. –
Hai risolto questo problema? Ho questo problema quando riattivo l'app dallo sfondo usando GCM. –