Java Code Examples for com.squareup.okhttp.OkHttpClient#setCache()

The following examples show how to use com.squareup.okhttp.OkHttpClient#setCache() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
Source File: RepoManager.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static OkHttpClient provideOkHttpClient(Credentials credentials, Context context) {

        OkHttpClient client = new OkHttpClient();
        client.interceptors().add(provideInterceptor(credentials));
        client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        client.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        client.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        client.setCache(provideCache(context));
        return client;
    }
 
Example 14
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 15
Source File: Downloader.java    From external-resources with Apache License 2.0 5 votes vote down vote up
public Downloader(@NonNull Context context, @NonNull OkHttpClient client,
    @NonNull Converter converter, @NonNull Url url, @NonNull Options options) {
  this.context = context.getApplicationContext();
  this.client = client;
  this.url = url;
  this.options = options;
  this.converter = converter;

  Cache cache = new Cache(context.getApplicationContext());

  client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setWriteTimeout(WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setCache(new com.squareup.okhttp.Cache(cache.getCacheDir(), cache.getCacheSize()));
}
 
Example 16
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 17
Source File: HostManager.java    From Kore with Apache License 2.0 4 votes vote down vote up
/**
     * 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))
//                        .indicatorsEnabled(BuildConfig.DEBUG)
                        .build();
            }
        }

        return currentPicasso;
    }