Java Examples for com.squareup.okhttp.Cache
The following java examples will help you to understand the usage of com.squareup.okhttp.Cache. These source code samples are taken from different open source projects.
Example 1
| Project: AreYouAlive-master File: ServiceGenerator.java View source code |
public static <S> S createService(Class<S> serviceClass, Context context) {
File cacheDirectory = new File(Environment.getExternalStorageDirectory(), "HttpCache");
// 10 MiB
int cacheSize = 10 * 1024 * 1024;
OkHttpClient client = new OkHttpClient();
Cache cache = null;
try {
cache = new Cache(cacheDirectory, cacheSize);
} catch (IOException e) {
e.printStackTrace();
}
client.setCache(cache);
RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint("http://areyoualive.org/").setConverter(new LoganSquareConverter()).setClient(new OkClient(client)).setLogLevel(RestAdapter.LogLevel.FULL);
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}Example 2
| Project: DevConSummit-master File: APIModule.java View source code |
@Provides
public RestAdapter provideRestAdapter() {
int SIZE_OF_CACHE = 1024;
OkHttpClient ok = new OkHttpClient();
ok.setReadTimeout(30, TimeUnit.SECONDS);
ok.setConnectTimeout(30, TimeUnit.SECONDS);
try {
Cache responseCache = new Cache(DevConApplication.getInstance().getCacheDir(), SIZE_OF_CACHE);
ok.setCache(responseCache);
} catch (Exception e) {
Log.d("OkHttp", "Unable to set http cache", e);
}
Executor executor = Executors.newCachedThreadPool();
return new RestAdapter.Builder().setExecutors(executor, executor).setClient(new OkClient(ok)).setEndpoint(DevConApplication.API_ENDPOINT).setRequestInterceptor(new ApiRequestInterceptor()).build();
}Example 3
| Project: tuchong-daily-android-master File: TuchongApplication.java View source code |
public void setPicasso() {
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new StethoInterceptor());
File cache = new File(this.getCacheDir(), PICASSO_CACHE);
if (!cache.exists()) {
//noinspection ResultOfMethodCallIgnored
cache.mkdirs();
}
try {
client.setCache(new Cache(cache, PICASSO_CACHE_SIZE));
} catch (IOException e) {
e.printStackTrace();
}
Picasso picasso = new Picasso.Builder(this).downloader(new OkHttpDownloader(client)).build();
Picasso.setSingletonInstance(picasso);
}Example 4
| Project: uberpay-wallet-master File: NetworkUtils.java View source code |
public static OkHttpClient getHttpClient(Context context) {
if (httpClient == null) {
httpClient = new OkHttpClient();
httpClient.setConnectionSpecs(Collections.singletonList(ConnectionSpec.MODERN_TLS));
// TODO HTC 300 Crashed due to Network fail - possibly increase timeout rate to 7000 ms
httpClient.setConnectTimeout(Constants.HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
// Setup cache
File cacheDir = new File(context.getCacheDir(), Constants.HTTP_CACHE_DIR);
Cache cache = new Cache(cacheDir, Constants.HTTP_CACHE_SIZE);
httpClient.setCache(cache);
}
return httpClient;
}Example 5
| Project: AndroidProjectTemplate-master File: AppApplication.java View source code |
@AfterInject
public void init() {
ACRA.init(this);
ACRA.getErrorReporter().setReportSender(acraSender);
if (BuildConfig.IS_DEBUGGING) {
LeakCanary.install(this);
Stetho.initialize(Stetho.newInitializerBuilder(this).enableDumpapp(Stetho.defaultDumperPluginsProvider(this)).enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)).build());
}
//FOR SAMPLE PURPOSE
OkHttpClient okHttpClient = new OkHttpClient().setCache(new Cache(getCacheDir(), 1024 * 1024 * 10));
okHttpClient.setReadTimeout(5, TimeUnit.SECONDS);
okHttpClient.setRetryOnConnectionFailure(true);
okHttpClient.setWriteTimeout(1, TimeUnit.MINUTES);
okHttpClient.setReadTimeout(5, TimeUnit.MINUTES);
twitterService = new RestAdapter.Builder().setEndpoint("https://api.twitter.com").setConverter(new GsonConverter(new Gson(), "UTF-8")).setClient(new OkClient(okHttpClient)).build().create(TwitterService.class);
}Example 6
| Project: IndiaSatelliteWeather-master File: HttpClient.java View source code |
private static void initializeHttpCache() {
try {
// 10 MiB
int cacheSize = 10 * 1024 * 1024;
Cache responseCache = new Cache(WeatherApplication.getContext().getCacheDir(), cacheSize);
okHttpClient.setCache(responseCache);
} catch (Exception e) {
CrashUtils.trackException("Can't set HTTP cache", e);
}
}Example 7
| Project: marvel-api-master File: RetrofitHttpClient.java View source code |
private static OkUrlFactory generateDefaultOkUrlFactory() {
OkHttpClient client = new com.squareup.okhttp.OkHttpClient();
client.setConnectTimeout(CONNECT_TIMEOUT_SEC, TimeUnit.SECONDS);
client.setReadTimeout(READ_TIMEOUT_SEC, TimeUnit.SECONDS);
try {
File cacheDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
Cache cache = new Cache(cacheDir, 1024);
client.setCache(cache);
} catch (IOException e) {
e.printStackTrace();
}
return new OkUrlFactory(client);
}Example 8
| Project: OpenMapKit-master File: NetworkUtils.java View source code |
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache, final SSLSocketFactory sslSocketFactory) {
OkHttpClient client = new OkHttpClient();
if (cache != null) {
client.setCache(cache);
}
if (sslSocketFactory != null) {
client.setSslSocketFactory(sslSocketFactory);
}
HttpURLConnection connection = new OkUrlFactory(client).open(url);
connection.setRequestProperty("User-Agent", MapboxUtils.getUserAgent());
return connection;
}Example 9
| Project: remusic-master File: HttpUtil.java View source code |
public static Bitmap getBitmapStream(Context context, String url, boolean forceCache) {
try {
File sdcache = context.getExternalCacheDir();
//File cacheFile = new File(context.getCacheDir(), "[缓å˜ç›®å½•]");
//30Mb
Cache cache = new Cache(sdcache.getAbsoluteFile(), 1024 * 1024 * 30);
mOkHttpClient.setCache(cache);
mOkHttpClient.setConnectTimeout(1000, TimeUnit.MINUTES);
mOkHttpClient.setReadTimeout(1000, TimeUnit.MINUTES);
Request.Builder builder = new Request.Builder().url(url);
if (forceCache) {
builder.cacheControl(CacheControl.FORCE_CACHE);
}
Request request = builder.build();
Response response = mOkHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return _decodeBitmapFromStream(response.body().byteStream(), 160, 160);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 10
| Project: sendtopulsar-master File: DataModule.java View source code |
static OkHttpClient createOkHttpClient(SendToPulsarApp app) {
OkHttpClient client = new OkHttpClient();
// Install an HTTP cache in the application cache directory.
try {
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
} catch (IOException e) {
Log.e(TAG, "Unable to install disk cache.", e);
}
return client;
}Example 11
| Project: Tower-master File: NetworkUtils.java View source code |
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache, final SSLSocketFactory sslSocketFactory) {
OkHttpClient client = new OkHttpClient();
if (cache != null) {
client.setCache(cache);
}
if (sslSocketFactory != null) {
client.setSslSocketFactory(sslSocketFactory);
}
HttpURLConnection connection = new OkUrlFactory(client).open(url);
connection.setRequestProperty("User-Agent", MapboxUtils.getUserAgent());
return connection;
}Example 12
| Project: U2020-mortar-flow-master File: DataModule.java View source code |
static OkHttpClient createOkHttpClient(Application app) {
OkHttpClient client = new OkHttpClient();
// Install an HTTP cache in the application cache directory.
try {
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
} catch (IOException e) {
Timber.e(e, "Unable to install disk cache.");
}
return client;
}Example 13
| Project: udacity-popular-movies-master File: DataModule.java View source code |
static OkHttpClient createOkHttpClient(Application app) {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(10, SECONDS);
client.setReadTimeout(10, SECONDS);
client.setWriteTimeout(10, SECONDS);
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
return client;
}Example 14
| Project: WeiBo_LH-master File: App.java View source code |
@Override
public void intercept(RequestFacade request) {
if (Network.isConnected(getApplicationContext())) {
// read from cache for 1 minute
int maxAge = 2;
request.addHeader("Cache-Control", "public, max-age=" + maxAge);
} else {
// tolerate 4-weeks stale
int maxStale = 60 * 60 * 24 * 28;
request.addHeader("Cache-Control", "public, only-if-cached, max-stale=" + maxStale);
}
}Example 15
| Project: WhereIsMyCurrency-master File: ApiModule.java View source code |
private static OkHttpClient createOkHttpClient(Application application) {
final OkHttpClient temporaryClient = new OkHttpClient();
temporaryClient.networkInterceptors().add(new StethoInterceptor());
try {
File cacheDirectory = application.getCacheDir();
Cache cache = new Cache(cacheDirectory, DISK_CACHE_SIZE);
temporaryClient.setCache(cache);
} catch (Exception e) {
if (BuildConfig.DEBUG) {
Log.e(TAG, "Unable to initialize OkHttpClient with disk cache.");
}
}
return temporaryClient;
}Example 16
| Project: BitcoinBlue-master File: DataModule.java View source code |
static OkHttpClient createOkHttpClient(BaseApplication app) {
OkHttpClient client = new OkHttpClient();
// Install an HTTP cache in the application cache directory.
try {
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
} catch (Exception e) {
Timber.e(e, "Unable to install disk cache.");
}
return client;
}Example 17
| Project: episodes-master File: EpisodesApplication.java View source code |
@Override
public void onCreate() {
super.onCreate();
instance = this;
// ensure the default settings are initialised at first launch,
// rather than waiting for the settings screen to be opened.
// do this before anything that needs these settings is instantiated.
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
autoRefreshHelper = AutoRefreshHelper.getInstance(this);
httpClient = new OkHttpClient();
try {
Cache httpCache = new Cache(getCacheDir(), 1024 * 1024);
httpClient.setCache(httpCache);
} catch (IOException e) {
Log.w(TAG, "Error initialising okhttp cache", e);
}
final ImageLoaderConfiguration imageLoaderConfig = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(imageLoaderConfig);
}Example 18
| Project: Git.NB-master File: GankRetrofit.java View source code |
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (Utils.isNetworkAvailable(Application.mContext)) {
CacheControl cacheControl = new CacheControl.Builder().maxAge(1, TimeUnit.HOURS).build();
// 有网络时 设置缓å˜è¶…æ—¶æ—¶é—´1个å°?æ—¶
response.newBuilder().header("Cache-Control", cacheControl.toString()).removeHeader("Pragma").build();
} else {
// æ— ç½‘ç»œæ—¶ï¼Œè®¾ç½®è¶…æ—¶ä¸º1周
CacheControl cacheControl = new CacheControl.Builder().maxAge(3, TimeUnit.DAYS).onlyIfCached().build();
response.newBuilder().header("Cache-Control", cacheControl.toString()).removeHeader("Pragma").build();
}
return response;
}Example 19
| Project: kc-android-master File: DataModule.java View source code |
static OkHttpClient createOkHttpClient(Application app) {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
client.setReadTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
// Install an HTTP cache in the application cache directory.
try {
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
} catch (IOException e) {
e.printStackTrace();
}
return client;
}Example 20
| Project: KingsCrossApp-master File: DataModule.java View source code |
static OkHttpClient createOkHttpClient(Application app) {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
client.setReadTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
// Install an HTTP cache in the application cache directory.
try {
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
} catch (IOException e) {
e.printStackTrace();
}
return client;
}Example 21
| Project: ponyville-live-android-master File: NetModule.java View source code |
public static OkHttpClient createOkHttpClient(Application app) {
OkHttpClient client = new OkHttpClient();
// Install an HTTP cache in the application cache directory.
try {
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, CACHE_SIZE);
client.setCache(cache);
} catch (IOException e) {
Timber.e(e, "Unable to install disk cache.");
}
return client;
}Example 22
| Project: sbt-android-master File: DebugView.java View source code |
private void refreshOkHttpCacheStats() {
// Shares the cache with apiClient, so no need to check both.
Cache cache = client.getCache();
int writeTotal = cache.getWriteSuccessCount() + cache.getWriteAbortCount();
int percentage = (int) ((1f * cache.getWriteAbortCount() / writeTotal) * 100);
okHttpCacheWriteErrorView.setText(cache.getWriteAbortCount() + " / " + writeTotal + " (" + percentage + "%)");
okHttpCacheRequestCountView.setText(String.valueOf(cache.getRequestCount()));
okHttpCacheNetworkCountView.setText(String.valueOf(cache.getNetworkCount()));
okHttpCacheHitCountView.setText(String.valueOf(cache.getHitCount()));
}Example 23
| Project: sthlmtraveling-master File: HttpHelper.java View source code |
/**
* Install an HTTP cache in the application cache directory.
*/
private void installHttpCache(final Context context) {
// Install an HTTP cache in the application cache directory.
try {
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(context.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
mClient.setCache(cache);
} catch (Throwable e) {
Log.e("HttpHelper", "Unable to install disk cache.");
}
}Example 24
| Project: TiM-master File: RestServiceFactory.java View source code |
public static <T> T createStatic(final Context context, String baseUrl, Class<T> clazz) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(new Cache(context.getApplicationContext().getCacheDir(), CACHE_SIZE));
okHttpClient.setConnectTimeout(40, TimeUnit.SECONDS);
RequestInterceptor interceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
//7-days cache
request.addHeader("Cache-Control", String.format("max-age=%d,max-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), Integer.valueOf(31536000)));
request.addHeader("Connection", "keep-alive");
}
};
RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl).setRequestInterceptor(interceptor).setClient(new OkClient(okHttpClient));
return builder.build().create(clazz);
}Example 25
| Project: Timber-master File: RestServiceFactory.java View source code |
public static <T> T createStatic(final Context context, String baseUrl, Class<T> clazz) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(new Cache(context.getApplicationContext().getCacheDir(), CACHE_SIZE));
okHttpClient.setConnectTimeout(40, TimeUnit.SECONDS);
RequestInterceptor interceptor = new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
//7-days cache
request.addHeader("Cache-Control", String.format("max-age=%d,max-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), Integer.valueOf(31536000)));
request.addHeader("Connection", "keep-alive");
}
};
RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl).setRequestInterceptor(interceptor).setClient(new OkClient(okHttpClient));
return builder.build().create(clazz);
}Example 26
| Project: github-plugin-master File: GitHubLoginFunction.java View source code |
/**
* okHttp connector to be used as backend for GitHub client.
* Uses proxy of jenkins
* If cache size > 0, uses cache
*
* @return connector to be used as backend for client
*/
private OkHttpConnector connector(GitHubServerConfig config) {
OkHttpClient client = new OkHttpClient().setProxy(getProxy(defaultIfBlank(config.getApiUrl(), GITHUB_URL)));
if (config.getClientCacheSize() > 0) {
Cache cache = toCacheDir().apply(config);
client.setCache(cache);
}
return new OkHttpConnector(new OkUrlFactory(client));
}Example 27
| Project: Rutgers-Course-Tracker-master File: RutgersCTModule.java View source code |
@Provides
@Singleton
public OkHttpClient providesOkHttpClient(Context context) {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
client.networkInterceptors().add(new StethoInterceptor());
File httpCacheDir = new File(context.getCacheDir(), context.getString(R.string.application_name));
// 50 MiB
long httpCacheSize = 50 * 1024 * 1024;
Cache cache = new Cache(httpCacheDir, httpCacheSize);
client.setCache(cache);
if (BuildConfig.DEBUG) {
try {
cache.evictAll();
} catch (IOException e) {
e.printStackTrace();
}
}
return client;
}Example 28
| Project: StartupNews-master File: OkHttpClientHelper.java View source code |
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder builder = request.newBuilder();
builder.addHeader("Accept-Language", "zh-cn");
builder.addHeader("Accept", "*/*");
if (mCookieFactory != null) {
builder.addHeader("Cookie", mCookieFactory.getCookie());
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
builder.header("User-Agent", WebSettings.getDefaultUserAgent(context));
} else {
builder.header("User-Agent", USER_AGENT);
}
// Add Cache Control only for GET methods
if (request.method().equals("GET")) {
if (NetworkUtils.isNetworkAvailable(context)) {
// 1 day
request.newBuilder().header("Cache-Control", "only-if-cached").build();
} else {
// 4 weeks stale
request.newBuilder().header("Cache-Control", "public, max-stale=2419200").build();
}
}
Response response = chain.proceed(request);
// Re-write response CC header to force use of cache
return response.newBuilder().header("Cache-Control", // 1 day
"public, max-age=86400").build();
}Example 29
| Project: cusnews-master File: Api.java View source code |
/**
* Init the http-client and cache.
*/
private static void initClient(Context cxt) {
// Create an HTTP client that uses a cache on the file system. Android applications should use
// their Context to get a cache directory.
OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.networkInterceptors().add(new StethoInterceptor());
File cacheDir = new File(cxt != null ? cxt.getCacheDir().getAbsolutePath() : System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
try {
sCache = new com.squareup.okhttp.Cache(cacheDir, sCacheSize);
} catch (IOException e) {
e.printStackTrace();
}
okHttpClient.setCache(sCache);
okHttpClient.setReadTimeout(3600, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(3600, TimeUnit.SECONDS);
sClient = new OkClient(okHttpClient);
}Example 30
| Project: popcorn-android-master File: PopcornApplication.java View source code |
public static OkHttpClient getHttpClient() {
if (sHttpClient == null) {
sHttpClient = new OkHttpClient();
int cacheSize = 10 * 1024 * 1024;
File cacheLocation = new File(PrefUtils.get(PopcornApplication.getAppContext(), Prefs.STORAGE_LOCATION, StorageUtils.getIdealCacheDirectory(PopcornApplication.getAppContext()).toString()));
cacheLocation.mkdirs();
com.squareup.okhttp.Cache cache = null;
try {
cache = new com.squareup.okhttp.Cache(cacheLocation, cacheSize);
} catch (Exception e) {
e.printStackTrace();
}
sHttpClient.setCache(cache);
}
return sHttpClient;
}Example 31
| Project: ACEMusicPlayer-master File: OkHttpDownloader.java View source code |
@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
HttpURLConnection connection = openConnection(uri);
connection.setUseCaches(true);
if (localCacheOnly) {
connection.setRequestProperty("Cache-Control", "only-if-cached,max-age=" + Integer.MAX_VALUE);
}
int responseCode = connection.getResponseCode();
if (responseCode >= 300) {
connection.disconnect();
throw new ResponseException(responseCode + " " + connection.getResponseMessage());
}
String responseSource = connection.getHeaderField(RESPONSE_SOURCE_OKHTTP);
if (responseSource == null) {
responseSource = connection.getHeaderField(RESPONSE_SOURCE_ANDROID);
}
long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
boolean fromCache = parseResponseSourceHeader(responseSource);
return new Response(connection.getInputStream(), fromCache, contentLength);
}Example 32
| Project: android-rssreader-master File: HttpLoaderImpl.java View source code |
/**
* Call this to reset the cache-size
*
* @param context
*/
public static void updateCacheSize(Context context) {
try {
HttpLoaderImpl fl = getInstance(context);
Cache cache = fl.client.getCache();
if (cache != null) {
cache.flush();
cache.close();
cache.delete();
}
fl.client.setCache(getCache(context));
} catch (IOException ex) {
Timber.w(ex, "Could not update Cachesize");
}
}Example 33
| Project: catwatch-master File: SnapshotProvider.java View source code |
/**
* Initializes cache after the bean is created
*/
@PostConstruct
public void init() {
Optional<File> cacheDirectoryOptional = getCacheDirectory();
if (cacheDirectoryOptional.isPresent()) {
Cache cache = new Cache(cacheDirectoryOptional.get(), cacheSize * MEGABYTE);
this.httpClient = new OkHttpClient().setCache(cache);
logger.info("Initialized http client with {} mb cache.", cacheSize);
} else {
this.httpClient = new OkHttpClient();
logger.warn("Initialized http client without cache.");
}
}Example 34
| Project: Dribble-master File: AppModule.java View source code |
static OkHttpClient createOkHttpClient(Application app) {
OkHttpClient client = new OkHttpClient();
try {
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
} catch (IOException e) {
Timber.e(e, "Unable to install disk cache.");
}
return client;
}Example 35
| Project: external-resources-master File: Downloader.java View source code |
public Resources load(@Cache.Policy int policy) throws ExternalResourceException { buildUrl(); Logger.i(ExternalResources.TAG, "Load configuration from url: " + url.build()); final CacheControl cacheControl; switch(policy) { case Cache.POLICY_NONE: cacheControl = new CacheControl.Builder().noCache().noStore().build(); break; case Cache.POLICY_OFFLINE: cacheControl = CacheControl.FORCE_CACHE; break; case Cache.POLICY_ALL: default: cacheControl = new CacheControl.Builder().build(); break; } Logger.v(ExternalResources.TAG, "CachePolicy: " + policy); Request request = new Request.Builder().url(url.build()).cacheControl(cacheControl).build(); try { Response response = client.newCall(request).execute(); int responseCode = response.code(); Logger.d(ExternalResources.TAG, "Response code: " + responseCode); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), policy, responseCode); } return converter.fromReader(response.body().charStream()); } catch (IOException e) { throw new ExternalResourceException(e); } }
Example 36
| Project: jAM-master File: OkHttpDownloader.java View source code |
@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
HttpURLConnection connection = openConnection(uri);
connection.setUseCaches(true);
if (localCacheOnly) {
connection.setRequestProperty("Cache-Control", "only-if-cached,max-age=" + Integer.MAX_VALUE);
}
int responseCode = connection.getResponseCode();
if (responseCode >= 300) {
connection.disconnect();
throw new ResponseException(responseCode + " " + connection.getResponseMessage());
}
String responseSource = connection.getHeaderField(RESPONSE_SOURCE_OKHTTP);
if (responseSource == null) {
responseSource = connection.getHeaderField(RESPONSE_SOURCE_ANDROID);
}
long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
boolean fromCache = parseResponseSourceHeader(responseSource);
return new Response(connection.getInputStream(), fromCache, contentLength);
}Example 37
| Project: JamsMusicPlayer-master File: OkHttpDownloader.java View source code |
@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
HttpURLConnection connection = openConnection(uri);
connection.setUseCaches(true);
if (localCacheOnly) {
connection.setRequestProperty("Cache-Control", "only-if-cached,max-age=" + Integer.MAX_VALUE);
}
int responseCode = connection.getResponseCode();
if (responseCode >= 300) {
connection.disconnect();
throw new ResponseException(responseCode + " " + connection.getResponseMessage());
}
String responseSource = connection.getHeaderField(RESPONSE_SOURCE_OKHTTP);
if (responseSource == null) {
responseSource = connection.getHeaderField(RESPONSE_SOURCE_ANDROID);
}
long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
boolean fromCache = parseResponseSourceHeader(responseSource);
return new Response(connection.getInputStream(), fromCache, contentLength);
}Example 38
| Project: picasso-helper-master File: OkHttpDownloaderWithSetting.java View source code |
@Override
public Response load(Uri uri, boolean localCacheOnly) throws IOException {
HttpURLConnection connection = openConnection(uri);
connection.setUseCaches(true);
if (localCacheOnly) {
connection.setRequestProperty("Cache-Control", "only-if-cached,max-age=" + maxAge);
}
int responseCode = connection.getResponseCode();
if (responseCode >= 300) {
connection.disconnect();
throw new ResponseException(responseCode + " " + connection.getResponseMessage());
}
String responseSource = connection.getHeaderField(RESPONSE_SOURCE_OKHTTP);
if (responseSource == null) {
responseSource = connection.getHeaderField(RESPONSE_SOURCE_ANDROID);
}
long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
boolean fromCache = parseResponseSourceHeader(responseSource);
return new Response(connection.getInputStream(), fromCache, contentLength);
}Example 39
| Project: PkRSS-master File: OkHttpDownloader.java View source code |
@Override
public String execute(Request request) throws IllegalArgumentException, IOException {
// Invalid URLs are a big no no
if (request.url == null || request.url.isEmpty()) {
throw new IllegalArgumentException("Invalid URL!");
}
// Start tracking download time
long time = System.currentTimeMillis();
// Empty response string placeholder
String responseStr;
// Handle cache
int maxCacheAge = request.skipCache ? 0 : cacheMaxAge;
// Build proper URL
String requestUrl = toUrl(request);
// Build the OkHttp request
com.squareup.okhttp.Request httpRequest = new com.squareup.okhttp.Request.Builder().addHeader("Cache-Control", "public, max-age=" + maxCacheAge).url(requestUrl).build();
try {
// Execute the built request and log its data
log("Making a request to " + requestUrl + (request.skipCache ? " [SKIP-CACHE]" : " [MAX-AGE " + maxCacheAge + "]"));
Response response = client.newCall(httpRequest).execute();
// Was this retrieved from cache?
if (response.cacheResponse() != null)
log("Response retrieved from cache");
// Convert response body to a string
responseStr = response.body().string();
log(TAG, "Request download took " + (System.currentTimeMillis() - time) + "ms", Log.INFO);
} catch (Exception e) {
log("Error executing/reading http request!", Log.ERROR);
e.printStackTrace();
throw new IOException(e.getMessage());
}
return responseStr;
}Example 40
| Project: SuperMvp-master File: RetrofitService.java View source code |
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetUtil.isConnected(MyApplication.getContext())) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
Logger.e("no network");
}
Response originalResponse = chain.proceed(request);
if (NetUtil.isConnected(MyApplication.getContext())) {
//有网的时候读接å?£ä¸Šçš„@Headers里的é…?ç½®ï¼Œä½ å?¯ä»¥åœ¨è¿™é‡Œè¿›è¡Œç»Ÿä¸€çš„设置
String cacheControl = request.cacheControl().toString();
return originalResponse.newBuilder().header("Cache-Control", cacheControl).removeHeader("Pragma").build();
} else {
return originalResponse.newBuilder().header("Cache-Control", "public, only-if-cached," + CACHE_STALE_SEC).removeHeader("Pragma").build();
}
}Example 41
| Project: js-android-app-master File: AppModule.java View source code |
@Singleton
@Named("webview_client")
@Provides
OkHttpClient provideWebViewClient(@ApplicationContext Context context) {
OkHttpClient client = new OkHttpClient();
File cacheDir = context.getApplicationContext().getCacheDir();
File okCache = new File(cacheDir, "ok-cache");
if (!okCache.exists()) {
boolean cachedCreated = okCache.mkdirs();
if (cachedCreated) {
int cacheSize = 50 * 1024 * 1024;
Cache cache = new Cache(okCache, cacheSize);
client.setCache(cache);
}
}
return client;
}Example 42
| Project: mobilecloud-15-master File: AcronymOps.java View source code |
/**
* Hook method dispatched by the GenericActivity framework to
* initialize the AcronymOps object after it's been created.
*
* @param view The currently active AcronymOps.View.
* @param firstTimeIn Set to "true" if this is the first time the
* Ops class is initialized, else set to
* "false" if called after a runtime
* configuration change.
*/
public void onConfiguration(AcronymOps.View view, boolean firstTimeIn) {
Log.d(TAG, "onConfiguration() called");
// Reset the mAcronymView WeakReference.
mAcronymView = new WeakReference<>(view);
if (firstTimeIn) {
// Store the Application context to avoid problems with
// the Activity context disappearing during a rotation.
mContext = view.getApplicationContext();
// Set up the HttpResponse cache that will be used by
// Retrofit.
mCache = new Cache(new File(mContext.getCacheDir(), CACHE_FILENAME), // Cache stores up to 1 MB.
1024 * 1024);
// Set up the client that will use this cache. Retrofit
// will use okhttp client to make network calls.
mOkHttpClient = new OkHttpClient();
if (mCache != null)
mOkHttpClient.setCache(mCache);
// Create a proxy to access the Acronym Service web
// service.
mAcronymWebServiceProxy = new RestAdapter.Builder().setEndpoint(AcronymWebServiceProxy.ENDPOINT).setClient(new OkClient(mOkHttpClient)).setLogLevel(// .setLogLevel(LogLevel.FULL)
LogLevel.NONE).build().create(AcronymWebServiceProxy.class);
}
}Example 43
| Project: programming-cloud-services-for-android-master File: AcronymOps.java View source code |
/**
* Hook method dispatched by the GenericActivity framework to
* initialize the AcronymOps object after it's been created.
*
* @param view The currently active AcronymOps.View.
* @param firstTimeIn Set to "true" if this is the first time the
* Ops class is initialized, else set to
* "false" if called after a runtime
* configuration change.
*/
public void onConfiguration(AcronymOps.View view, boolean firstTimeIn) {
Log.d(TAG, "onConfiguration() called");
// Reset the mAcronymView WeakReference.
mAcronymView = new WeakReference<>(view);
if (firstTimeIn) {
// Store the Application context to avoid problems with
// the Activity context disappearing during a rotation.
mContext = view.getApplicationContext();
// Set up the HttpResponse cache that will be used by
// Retrofit.
mCache = new Cache(new File(mContext.getCacheDir(), CACHE_FILENAME), // Cache stores up to 1 MB.
1024 * 1024);
// Set up the client that will use this cache. Retrofit
// will use okhttp client to make network calls.
mOkHttpClient = new OkHttpClient();
if (mCache != null)
mOkHttpClient.setCache(mCache);
// Create a proxy to access the Acronym Service web
// service.
mAcronymWebServiceProxy = new RestAdapter.Builder().setEndpoint(AcronymWebServiceProxy.ENDPOINT).setClient(new OkClient(mOkHttpClient)).setLogLevel(// .setLogLevel(LogLevel.FULL)
LogLevel.NONE).build().create(AcronymWebServiceProxy.class);
}
}Example 44
| Project: PushApp-Android-master File: DataModule.java View source code |
@Provides
@Singleton
OkHttpClient provideOkHttp(Cache cache) {
OkHttpClient okHttp = new OkHttpClient();
okHttp.setCache(cache);
okHttp.setConnectTimeout(30, TimeUnit.SECONDS);
okHttp.setReadTimeout(30, TimeUnit.SECONDS);
okHttp.setWriteTimeout(30, TimeUnit.SECONDS);
okHttp.networkInterceptors().add(new StethoInterceptor());
return okHttp;
}Example 45
| Project: tapchat-android-master File: TapchatModule.java View source code |
@Provides
@Singleton
public OkHttpClient provideOkHttp(SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier) {
try {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(new Cache(mAppContext.getCacheDir(), MAX_CACHE_SIZE));
okHttpClient.setHostnameVerifier(hostnameVerifier);
okHttpClient.setSslSocketFactory(sslSocketFactory);
return okHttpClient;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}Example 46
| Project: CanvasAPI-master File: CanvasRestAdapter.java View source code |
@Override
public Response intercept(Chain chain) throws IOException {
com.squareup.okhttp.Request request = chain.request();
Response response = chain.proceed(request);
// Displayed cached data will always be followed by a response from the server with the latest data.
return response.newBuilder().header("Cache-Control", //60*60*24*14 = 1209600 2 weeks; Essentially means cached data will only be valid offline for 2 weeks. When network is available, the cache is always updated on every request.
"public, max-age=1209600").build();
}Example 47
| Project: Kore-master File: HostManager.java View source code |
/**
* Returns the current host {@link Picasso} image downloader
* @return {@link Picasso} instance suitable to download images from the current xbmc
*/
public Picasso getPicasso() {
if (currentPicasso == null) {
currentHostInfo = getHostInfo();
if (currentHostInfo != null) {
// currentPicasso = new Picasso.Builder(context)
// .downloader(new BasicAuthUrlConnectionDownloader(context,
// currentHostInfo.getUsername(), currentHostInfo.getPassword()))
// .indicatorsEnabled(BuildConfig.DEBUG)
// .build();
// Http client should already handle authentication
OkHttpClient picassoClient = getConnection().getOkHttpClient().clone();
// OkHttpClient picassoClient = new OkHttpClient();
// // Set authentication on the client
// if (!TextUtils.isEmpty(currentHostInfo.getUsername())) {
// picassoClient.interceptors().add(new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
//
// String creds = currentHostInfo.getUsername() + ":" + currentHostInfo.getPassword();
// Request newRequest = chain.request().newBuilder()
// .addHeader("Authorization",
// "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP))
// .build();
// return chain.proceed(newRequest);
// }
// });
// }
// Set cache
File cacheDir = NetUtils.createDefaultCacheDir(context);
long cacheSize = NetUtils.calculateDiskCacheSize(cacheDir);
picassoClient.setCache(new com.squareup.okhttp.Cache(cacheDir, cacheSize));
currentPicasso = new Picasso.Builder(context).downloader(new OkHttpDownloader(picassoClient)).build();
}
}
return currentPicasso;
}Example 48
| Project: AndroidReferenceArchitecture-master File: AppModule.java View source code |
@Provides
@Singleton
public OkHttpClient provideOkHttpClient(ReferenceArchitectureApp context) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(new Cache(context.getCacheDir(), CACHE_SIZE));
return okHttpClient;
}Example 49
| Project: NasaPic-master File: RetrofitWithCacheInteractor.java View source code |
public Cache createHttpClientCache(Context context) { try { File cacheDir = context.getDir("service_api_cache", Context.MODE_PRIVATE); return new Cache(cacheDir, HTTP_CACHE_SIZE_IN_BYTES); } catch (IOException e) { e.printStackTrace(); return null; } }
Example 50
| Project: Trackables-master File: DataModule.java View source code |
@Singleton
@Provides
public OkHttpClient provideOkHttpClient(Context context) {
OkHttpClient client = new OkHttpClient();
File path = new File(context.getCacheDir(), "okHttp");
path.mkdirs();
client.setCache(new Cache(path, AppConstants.OKHTTP_DISK_CACHE_SIZE));
return client;
}Example 51
| Project: Blip-master File: BlipApplication.java View source code |
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
mInstance = this;
int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(getCacheDir(), cacheSize);
client.setCache(cache);
SharedPrefs.create(this);
SpeechSynthesizer.create(this);
}Example 52
| Project: weixin4j-master File: OkHttpClient2Factory.java View source code |
public OkHttpClient2Factory setCache(Cache cache) {
okClient.setCache(cache);
return this;
}Example 53
| Project: Pioneer-master File: DataModule.java View source code |
static OkHttpClient createOkHttpClient(Application app) {
OkHttpClient client = new OkHttpClient();
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
return client;
}Example 54
| Project: wallsplash-android-master File: UnsplashApi.java View source code |
@Override
public void intercept(RequestFacade request) {
request.addHeader("Cache-Control", "public, max-age=" + 60 * 60 * 4);
}Example 55
| Project: ClubSeed-master File: AppUtils.java View source code |
/**
* fetch the json string from url
*
* @param url
* @return
*/
public static String getJSONString(String url) throws IOException {
Cache cache = new Cache(Environment.getExternalStorageDirectory(), 10 * 1024 * 1024);
client.setCache(cache);
Request listRequest = new Request.Builder().url(url).build();
String jsonString = client.newCall(listRequest).execute().body().string();
return jsonString;
}Example 56
| Project: GankApp-master File: GankCloudApi.java View source code |
@Override
public void intercept(RequestFacade request) {
request.addHeader("Cache-Control", "public, max-age=" + 60 * 60 * 4);
request.addHeader("Content-Type", "application/json");
}Example 57
| Project: gojira-master File: DataModule.java View source code |
@Provides
@Singleton
OkHttpClient provideOkHttpClient(Application app) {
OkHttpClient client = new OkHttpClient();
// Install an HTTP cache in the internal cache directory
File cacheDir = new File(app.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
return client;
}Example 58
| Project: Sky31Radio-master File: DataModule.java View source code |
@Provides
@Singleton
OkHttpClient provideOkHttp(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(cache);
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
return okHttpClient;
}Example 59
| Project: TruckMuncher-Android-master File: GlobalModule.java View source code |
public static void configureHttpCache(Context context, OkHttpClient client) {
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(context.getApplicationContext().getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
}Example 60
| Project: githot-master File: DataModule.java View source code |
@Provides
@Singleton
OkHttpClient provideOkHttp(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(cache);
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
return okHttpClient;
}Example 61
| Project: iview-android-tv-master File: HttpApiBase.java View source code |
private Cache createCache(Context context) { File cacheDir = createDefaultCacheDir(context, getCachePath()); long cacheSize = calculateDiskCacheSize(cacheDir); Log.i(TAG, "iview API disk cache:" + cacheDir + ", size:" + (cacheSize / 1024 / 1024) + "MB"); return new Cache(cacheDir, cacheSize); }
Example 62
| Project: Mizuu-master File: MizuuApplication.java View source code |
/**
* OkHttpClient singleton with 2 MB cache.
* @return
*/
public static OkHttpClient getOkHttpClient() {
if (mOkHttpClient == null) {
mOkHttpClient = new OkHttpClient();
File cacheDir = getContext().getCacheDir();
Cache cache = new Cache(cacheDir, 2 * 1024 * 1024);
mOkHttpClient.setCache(cache);
}
return mOkHttpClient;
}Example 63
| Project: platform-android-master File: AppModule.java View source code |
private static OkHttpClient createOkHttpClient(Context app) {
OkHttpClient client = new OkHttpClient();
File cacheDir = new File(app.getApplicationContext().getCacheDir(), "ushahidi-android-http-cache");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
client.setCache(cache);
return client;
}Example 64
| Project: tomahawk-android-master File: Store.java View source code |
@Override
public void intercept(RequestFacade request) {
if (!NetworkUtils.isNetworkAvailable()) {
// tolerate 1-week stale
int maxStale = 60 * 60 * 24 * 7;
request.addHeader("Cache-Control", "public, max-stale=" + maxStale);
}
request.addHeader("Content-type", "application/json; charset=utf-8");
}Example 65
| Project: save-for-offline-master File: PageSaver.java View source code |
public void setCache(File cacheDirectory, long maxCacheSize) {
Cache cache = (new Cache(cacheDirectory, maxCacheSize));
client.setCache(cache);
}