Модификация: кешировать каждый запрос - PullRequest
0 голосов
/ 10 сентября 2018

Я новичок в Android, и я хотел бы кэшировать каждый ответ сервера. Я использую модификацию, и я использую "ServiceGenerator". У меня есть это сообщение об ошибке: ".... 'java.lang.String okhttp3.ResponseBody.string ()' для ссылки на пустой объект" Когда мое устройство находится в автономном режиме. И у меня нет каталога http-кеша. Пожалуйста помоги! Вот мой код:

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(BASE_URL);

private static Retrofit retrofit = builder.build();

private static OkHttpClient.Builder httpClient =
        new OkHttpClient().newBuilder();

public static <S> S createService(Class<S> serviceClass, final Context context) {
    // adding cache
    Cache cache = new Cache(context.getCacheDir(), cacheSize);
    httpClient.cache(cache);
    // adding interceptor
    httpClient.addInterceptor(provideInterceptor(context));
    builder.client(httpClient.build());
    retrofit = builder.build();
    builder.client(httpClient.build());
    return retrofit.create(serviceClass);
}

// add caching logic to retrofit
static Interceptor provideInterceptor(final Context context){
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if(isThereInternet(context)){
                // if there is internet connection get the data just when it is younger than 12 Hours
                request = request.newBuilder().header("Cache-Control", "public, max-age=" + (12 * 60 *60)).build();
                Log.e("Interceptor " , "there is internet");
            } else {
                // load from cache not older than 7 days
                request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
            }
            return chain.proceed(request);
        }
    };

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...