我是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);
}
};
}