com.squareup.okhttp.Cache Java Examples

The following examples show how to use com.squareup.okhttp.Cache. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestServiceFactory.java    From Muzesto with GNU General Public License v3.0 6 votes vote down vote up
public static <T> T create(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 #2
Source File: App.java    From PhotoDiscovery with Apache License 2.0 5 votes vote down vote up
private void initPicasso() {
  File cacheDirectory = new File(getCacheDir().getAbsolutePath(), "OKHttpCache");

  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setCache(new Cache(cacheDirectory, Integer.MAX_VALUE));

  /** Dangerous interceptor that rewrites the server's cache-control header. */
  okHttpClient.networkInterceptors().add(new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
      Response originalResponse = chain.proceed(chain.request());
      return originalResponse.newBuilder()
          .header("Cache-Control", "public, max-age=432000")
          .header("Pragma", "")
          .build();
    }
  });

  OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);

  Picasso.Builder builder = new Picasso.Builder(this);
  builder.downloader(okHttpDownloader);

  Picasso picasso = builder.build();
  //picasso.setIndicatorsEnabled(true);
  //picasso.setLoggingEnabled(true);
  Picasso.setSingletonInstance(picasso);
}
 
Example #3
Source File: HttpClient.java    From IndiaSatelliteWeather with GNU General Public License v2.0 5 votes vote down vote up
private static void initializeHttpCache() {
    try {
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache responseCache = new Cache(WeatherApplication.getContext().getCacheDir(), cacheSize);
        okHttpClient.setCache(responseCache);
    } catch (Exception e) {
        CrashUtils.trackException("Can't set HTTP cache", e);
    }
}
 
Example #4
Source File: OkHttpDownloader.java    From PkRSS with Apache License 2.0 5 votes vote down vote up
public OkHttpDownloader(Context context) {
	this.client.setConnectTimeout(connectTimeout, TimeUnit.SECONDS);
	this.client.setReadTimeout(readTimeout, TimeUnit.SECONDS);

	try {
		File cacheDir = new File(context.getCacheDir().getAbsolutePath() + this.cacheDir);
		this.client.setCache(new Cache(cacheDir, cacheSize));
	} catch (Exception e) {
		Log.e(TAG, "Error configuring Downloader cache! \n" + e.getMessage());
	}
}
 
Example #5
Source File: WebModule.java    From Qiitanium with MIT License 5 votes vote down vote up
@Singleton
@Provides
public OkHttpClient provideOkHttpClient(Application app) {
  final int size = ResUtils.getInteger(app, R.integer.http_disk_cache_size);

  final OkHttpClient client = new OkHttpClient();
  File cacheDir = new File(app.getCacheDir(), "http");
  Cache cache = new Cache(cacheDir, size);
  client.setCache(cache);

  return client;
}
 
Example #6
Source File: NetworkUtils.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #7
Source File: NetworkManager.java    From android-skeleton-project with MIT License 5 votes vote down vote up
private OkUrlFactory generateDefaultOkUrlFactory() {
            OkHttpClient client = new com.squareup.okhttp.OkHttpClient();

            try {
                Cache responseCache = new Cache(baseContext.getCacheDir(), SIZE_OF_CACHE);
                client.setCache(responseCache);
            } catch (Exception e) {
//                Log.d(TAG, "Unable to set http cache", e);
            }

            client.setConnectTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
            client.setReadTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS);
            return new OkUrlFactory(client);
        }
 
Example #8
Source File: TapchatModule.java    From tapchat-android with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: DataModule.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
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 #10
Source File: DataModule.java    From dagger2-example with MIT License 5 votes vote down vote up
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, DISK_CACHE_SIZE);
        client.setCache(cache);
    } catch(IOException e) {
        Log.e("DatModule", "Unable to install disk cache.", e);
    }

    return client;
}
 
Example #11
Source File: AcronymOps.java    From mobilecloud-15 with Apache License 2.0 5 votes vote down vote up
/**
 * 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(LogLevel.FULL)
            .setLogLevel(LogLevel.NONE)
            .build()
            .create(AcronymWebServiceProxy.class);
    } 
}
 
Example #12
Source File: HttpApiBase.java    From iview-android-tv with MIT License 5 votes vote down vote up
private void ensureCache() {
    if (useCache && client.getCache() == null) {
        Cache cache = createCache(getContext());
        if (cache != null) {
            client.setCache(cache);
        }
    }
}
 
Example #13
Source File: DataModule.java    From Sky31Radio with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
OkHttpClient provideOkHttp(Cache cache) {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setCache(cache);
    okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
    return okHttpClient;
}
 
Example #14
Source File: DefaultServiceContainer.java    From android-clean-architecture-mvp with Apache License 2.0 5 votes vote down vote up
private Cache createOkHttpCache() {
    try {
        File directory = new File(mContext.getCacheDir(), "ok-http");
        return new Cache(directory, 3000000);
    } catch (IOException e) {
        return null;
    }
}
 
Example #15
Source File: DataModule.java    From githot with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
OkHttpClient provideOkHttp(Cache cache) {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setCache(cache);
    okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
    return okHttpClient;
}
 
Example #16
Source File: LineRetrofit.java    From Gank-Veaer with GNU General Public License v3.0 5 votes vote down vote up
LineRetrofit() {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(12, TimeUnit.SECONDS);
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    cache = new Cache(FileUtils.getHttpCacheDir(), cacheSize);
    client.setCache(cache);
    client.networkInterceptors().add(new CacheInterceptor());

    RestAdapter restAdapter = new RestAdapter.Builder().setClient(new OkClient(client))
        .setEndpoint("http://gank.avosapps.com/api/")
        .setConverter(new GsonConverter(gson))
        .build();
    service = restAdapter.create(Line.class);
}
 
Example #17
Source File: DataModule.java    From Pioneer with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: MirrorApplication.java    From mirror with Apache License 2.0 5 votes vote down vote up
private void initializeOkHttp() {
    Cache cache = new Cache(new File(getCacheDir(), "http"), 25 * 1024 * 1024);

    mOkHttpClient = new OkHttpClient();
    mOkHttpClient.setCache(cache);
    mOkHttpClient.setConnectTimeout(30, SECONDS);
    mOkHttpClient.setReadTimeout(30, SECONDS);
    mOkHttpClient.setWriteTimeout(30, SECONDS);
}
 
Example #19
Source File: PageSaver.java    From save-for-offline with GNU General Public License v2.0 4 votes vote down vote up
public void setCache (File cacheDirectory, long maxCacheSize) {
	Cache cache = (new Cache(cacheDirectory, maxCacheSize));
	client.setCache(cache);
}
 
Example #20
Source File: HttpApiBase.java    From iview-android-tv with MIT License 4 votes vote down vote up
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 #21
Source File: NetworkUtils.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache) {
    return getHttpURLConnection(url, cache, null);
}
 
Example #22
Source File: NetworkUtils.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static Cache getCache(final File cacheDir, final int maxSize) throws IOException {
    return new Cache(cacheDir, maxSize);
}
 
Example #23
Source File: GithubAccessor.java    From markdown-doclet with GNU General Public License v3.0 4 votes vote down vote up
private OkHttpConnector createCachedHttpConnector() {
    final File cacheDirectory = getCacheDirectory();
    final Cache cache = new Cache(cacheDirectory, this.cacheSize);
    return new OkHttpConnector(new OkUrlFactory(new OkHttpClient().setCache(cache)));
}