Example usage for com.squareup.okhttp OkHttpClient setCache

List of usage examples for com.squareup.okhttp OkHttpClient setCache

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient setCache.

Prototype

public OkHttpClient setCache(Cache cache) 

Source Link

Usage

From source file:de.uni_weimar.m18.backupfestival.network.WpJsonApi.java

License:Apache License

public WpJsonApi() {
    Cache cache = null;/*w ww. j  av a  2  s  .  co m*/
    OkHttpClient okHttpClient = null;

    try {
        File cacheDir = new File(FestivalApplication.getContext().getCacheDir().getPath(), "data.json");
        cache = new Cache(cacheDir, 10 * 1024 * 1024);
        okHttpClient = new OkHttpClient();
        okHttpClient.setCache(cache);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error during OkHttpClient init: " + e.getMessage());
        // TODO: do something meaningful? - File error handling?
    }

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(ENDPOINT)
            .setClient(new OkClient(okHttpClient)).setConverter(new GsonConverter(gson))
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Cache-Control", "public, max-age=" + 60 * 60 * 4);
                }
            }).build();
    mWebService = restAdapter.create(WpJsonService.class);
}

From source file:es.upv.grycap.coreutils.fiber.http.Http2Clients.java

License:Apache License

/**
 * Creates a {@link OkHttpClient} instance and configures it with a cache. The same instance is used across the application to
 * benefit from a common cache storage and to prevent cache corruption. The cache directory is created private to the user who
 * runs the application and its content is deleted when the JVM starts its shutting down sequence.
 * @return A {@link OkHttpClient} instance that can be used everywhere in the application.
 *//*w w  w  . j a v  a  2  s  .  co m*/
private static OkHttpClient client() {
    return COREUTILS_CONTEXT.getClient(OkHttpClient.class, "coreutils-fiber", () -> {
        final OkHttpClient client = new FiberOkHttpClient();
        try {
            // load default configuration
            final Config config = new Configurer().loadConfig(null, "coreutils");
            final long tmp = config.getBytes("coreutils.clients.http2.cache-size");
            final long cacheSize = CACHE_SIZE_RANGE.contains(tmp) ? tmp : CACHE_SIZE_RANGE.lowerEndpoint();
            // create the cache directory            
            final File cacheDir = createTempDirectory("coreutils-okhttp-cache-",
                    asFileAttribute(fromString("rwx------"))).toFile();
            final Http2ClientShutdownListener shutdownListener = new Http2ClientShutdownListener(cacheDir);
            COREUTILS_CONTEXT.addShutdownListener(shutdownListener, Http2ClientShutdownListener.class,
                    "coreutils-fiber");
            final Cache cache = new Cache(cacheDir, cacheSize);
            client.setCache(cache);
        } catch (IOException e) {
            LOGGER.error("Failed to create directory cache", e);
        }
        return client;
    });
}

From source file:me.hoangchunghien.popularmovies.data.api.ApiModule.java

License:Apache License

@Provides
@Singleton//from ww  w  .ja va  2 s .  c o  m
OkHttpClient provideOkHttpClient(@ForApplication Context 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;
}

From source file:org.amahi.anywhere.server.ApiModule.java

License:Open Source License

@Provides
@Singleton//  w ww . j a v  a  2 s  .  c om
OkHttpClient provideHttpClient(Cache httpCache) {
    OkHttpClient httpClient = new OkHttpClient();

    httpClient.setCache(httpCache);

    return httpClient;
}

From source file:org.edx.mobile.discussion.DiscussionAPI.java

License:Open Source License

@Inject
public DiscussionAPI(Context context, Config config) {
    this.context = context;
    this.config = config;
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();

    OkHttpClient oauthBasedClient = new OkHttpClient();
    File cacheDirectory = new File(context.getFilesDir(), "http-cache");
    if (!cacheDirectory.exists()) {
        cacheDirectory.mkdirs();/*from   w ww  .java 2s.  com*/
    }
    Cache cache = new com.squareup.okhttp.Cache(cacheDirectory, cacheSize);
    oauthBasedClient.setCache(cache);
    //  oauthBasedClient.interceptors().add(new GzipRequestInterceptor());
    oauthBasedClient.interceptors().add(new OauthHeaderRequestInterceptor(context));
    oauthBasedClient.interceptors().add(new LoggingInterceptor());
    RestAdapter restAdapter = new RestAdapter.Builder().setClient(new OkClient(oauthBasedClient))
            .setEndpoint(config.getApiHostURL()).setConverter(new GsonConverter(gson))
            //      .setRequestInterceptor(new OfflineRequestInterceptor(context, 60))
            .setErrorHandler(new RetroHttpExceptionHandler()).setLogLevel(RestAdapter.LogLevel.FULL).build();
    discussionService = restAdapter.create(DiscussionService.class);
}

From source file:org.tomahawk.libtomahawk.infosystem.hatchet.HatchetInfoPlugin.java

License:Open Source License

public HatchetInfoPlugin() {
    RequestInterceptor requestInterceptor = new RequestInterceptor() {
        @Override/*www .  jav a2  s  .c  o  m*/
        public void intercept(RequestFacade request) {
            if (!TomahawkUtils.isNetworkAvailable()) {
                int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
                request.addHeader("Cache-Control", "public, max-stale=" + maxStale);
            }
        }
    };
    OkHttpClient okHttpClient = new OkHttpClient();
    File cacheDir = new File(TomahawkApp.getContext().getCacheDir(), "responseCache");
    try {
        Cache cache = new Cache(cacheDir, 1024 * 1024 * 20);
        okHttpClient.setCache(cache);
    } catch (IOException e) {
        Log.e(TAG, "<init>: " + e.getClass() + ": " + e.getLocalizedMessage());
    }
    RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.BASIC)
            .setEndpoint(HATCHET_BASE_URL).setConverter(new JacksonConverter(InfoSystemUtils.getObjectMapper()))
            .setRequestInterceptor(requestInterceptor).setClient(new OkClient(okHttpClient)).build();
    mHatchet = restAdapter.create(Hatchet.class);
}

From source file:org.xbmc.kore.host.HostManager.java

License:Open Source License

/**
 * Returns the current host {@link Picasso} image downloader
 * @return {@link Picasso} instance suitable to download images from the current xbmc
 *//*  w w w  .ja v a 2 s.  com*/
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;
}

From source file:ph.devcon.android.base.module.APIModule.java

License:Apache License

@Provides
public RestAdapter provideRestAdapter() {
    int SIZE_OF_CACHE = 1024;
    OkHttpClient ok = new OkHttpClient();
    ok.setReadTimeout(30, TimeUnit.SECONDS);
    ok.setConnectTimeout(30, TimeUnit.SECONDS);
    try {//from  ww w . ja  v  a 2 s .  com
        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())
            //                .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new AndroidLog("RETROFIT"))
            .build();
}