@Override protected LiteClient initClient(ClientSettings settings) { if(client==null) client = new OkHttpClient(); client.setProxy(settings.getProxy()).setProxySelector(settings.getProxySelector()).setSocketFactory(settings.getSocketFactory()) .setSslSocketFactory(settings.getSslSocketFactory()) .setHostnameVerifier(settings.getHostnameVerifier()).setFollowSslRedirects(settings.isFollowSslRedirects()) .setFollowRedirects(settings.isFollowRedirects()); client.setRetryOnConnectionFailure(settings.getMaxRetryCount()>0); client.setConnectTimeout(settings.getConnectTimeout(), TimeUnit.MILLISECONDS); client.setReadTimeout(settings.getReadTimeout(),TimeUnit.MILLISECONDS); client.setWriteTimeout(settings.getWriteTimeout(), TimeUnit.MILLISECONDS); client.setCookieHandler(cookieHandler); if(settings.getCacheDir()!=null){ client.setCache(new Cache(settings.getCacheDir(),settings.getCacheMaxSize())); } return new Ok2Lite(client); }
public GitHub initGithub() { String tmpDirPath = System.getProperty("java.io.tmpdir"); File cacheDirectoryParent = new File(tmpDirPath); File cacheDirectory = new File(cacheDirectoryParent, "okhttpCache"); if (!cacheDirectory.exists()) { cacheDirectory.mkdir(); } Cache cache = new Cache(cacheDirectory, 100 * 1024 * 1024); try { return GitHubBuilder.fromCredentials() .withRateLimitHandler(RateLimitHandler.WAIT) .withAbuseLimitHandler(AbuseLimitHandler.WAIT) .withConnector(new OkHttpConnector(new OkUrlFactory(new OkHttpClient().setCache(cache)))) .build(); } catch (IOException e) { throw new RuntimeException(e); } }
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); }
@Provides @Singleton OkHttpClient provideOkHttpClient(Context context) { OkHttpClient client = new OkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); try { Cache cache = new Cache(context.getCacheDir(), 10 * 1024 * 1024); // 10 MiB client.setCache(cache); } catch (IOException e) { Toast.makeText(context, "Cannot create cache for http responses", Toast.LENGTH_SHORT).show(); } return client; }
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); }
public static void init(AppStructureConfig.HttpConfig config){ if(config == null){ throw new IllegalArgumentException("OkHttpComponent HttpConfig initialization parameters can not be NULL!"); } if(mOkHttpClient == null){ synchronized (OkHttpComponent.class){ if(mOkHttpClient == null){ File cacheDir = new File(AppStructure.getInstance().getCacheDir(), config.getCacheDir()); mOkHttpClient = new OkHttpClient(); mOkHttpClient.setCache(new Cache(cacheDir, config.getCacheSize())); mOkHttpClient.setConnectTimeout(config.getConnectTimeout(), TimeUnit.MILLISECONDS); mOkHttpClient.setReadTimeout(config.getReadTimeout(), TimeUnit.MILLISECONDS); if(AppStructure.isDebug()){ TLog.i(LOG_TAG,"OkHttpComponent initialization!"); } } } } }
@Inject public DefaultNetworkRequestProvider(@NonNull Context applicationContext, @NonNull AppStringsProvider appStringsProvider) { mOkHttpClient = new OkHttpClient(); mOkHttpClient.setConnectTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); mOkHttpClient.setReadTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); mOkHttpClient.setWriteTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); // Configure a response cache for OkHttp so we get some free bandwidth / battery preservation. File responseCacheDirectory = new File(applicationContext.getCacheDir(), RESPONSE_CACHE_DIRECTORY); mOkHttpClient.setCache(new Cache(responseCacheDirectory, RESPONSE_CACHE_SIZE_MEGABYTES)); mConnectivityManager = (ConnectivityManager) applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE); mApiKey = appStringsProvider.getString(R.string.football_api_key); }
public static BibleGatewayService instance(@NonNull Context context) { if (sService == null) { final Cache cache = new Cache(new File(context.getCacheDir(), HTTP_CACHE_FILE_NAME), HTTP_CACHE_SIZE); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS); okHttpClient.setReadTimeout(30, TimeUnit.SECONDS); okHttpClient.setCache(cache); okHttpClient.interceptors().add(interceptor); Retrofit retrofit = new Retrofit.Builder(). baseUrl(BibleGatewayService.API_BASE_URL). addConverterFactory(GsonConverterFactory.create()). addCallAdapterFactory(RxJavaCallAdapterFactory.create()). client(okHttpClient). build(); sService = retrofit.create(BibleGatewayService.class); } return sService; }
@Provides @Singleton public OkHttpClient providesOkHttpClient(Context context) { OkHttpClient client = new OkHttpClient(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); client.interceptors().add(interceptor); client.networkInterceptors().add(new StethoInterceptor()); File httpCacheDir = new File(context.getCacheDir() + "/okhttp"); httpCacheDir.mkdirs(); cleanDir(httpCacheDir); long httpCacheSize = 50 * 1024 * 1024; // 50 MiB Cache cache = new Cache(httpCacheDir, httpCacheSize); client.setCache(cache); return client; }
static OkHttpClient createOkHttpClient(final Context context) { OkHttpClient client = new OkHttpClient(); // Install an HTTP cache in the application cache directory. try { final File cacheDir = new File(context.getCacheDir(), "http"); final Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE); client.setCache(cache); } catch (IOException e) { //Timber.e(e, "Unable to install disk cache."); } return client; }
@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()) // .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new AndroidLog("RETROFIT")) .build(); }
@Provides public RestAdapter provideRestAdapter(MockWebServer mockWebServer) { 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(mockWebServer.getUrl("/").toString()) .setRequestInterceptor(new ApiRequestInterceptor()) .build(); }
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() { PreferencesUtility prefs = PreferencesUtility.getInstance(context); @Override public void intercept(RequestFacade request) { //7-days cache request.addHeader("Cache-Control", String.format("max-age=%d,%smax-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), prefs.loadArtistImages() ? "" : "only-if-cached,", 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); }
@Lazy @Bean @ConditionalOnMissingBean public Cache okHttp2Cache() throws IOException { File cacheDir = getCacheDir("okhttp2-cache"); return new Cache(cacheDir, properties.getCache().getSize()); }
@Provides @Singleton public OkHttpClient providesOkHttpClient(Application application) { OkHttpClient client = new OkHttpClient(); client.setCache(new Cache(application.getCacheDir(), CACHE_SIZE)); HttpLoggingInterceptor logger = new HttpLoggingInterceptor(); logger.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.HEADERS : HttpLoggingInterceptor.Level.NONE); client.interceptors().add(logger); return client; }
@SuppressWarnings("ResultOfMethodCallIgnored") private NetworkManager(File cache, long size) { client = new OkHttpClient(); if (cache != null) { if (!cache.exists()) { cache.mkdirs(); } Cache c = new Cache(cache, size); client.setCache(c); } }
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); }
private DownloadManager(Context ctx) { mOkHttpClient = new OkHttpClient(); int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(ctx.getExternalCacheDir(), cacheSize); mOkHttpClient.setCache(cache); }
public static OkHttpClient getInstance(Context context, String cacheDirPath) { if (singleton == null) { synchronized (OkHttpUtil.class) { if (singleton == null) { File cacheDir = new File(context.getCacheDir(), cacheDirPath); singleton = new OkHttpClient(); singleton.setCache(new Cache(cacheDir, RESPONSE_CACHE_SIZE)); singleton.setConnectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS); singleton.setReadTimeout(HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS); } } } return singleton; }
@Provides @Singleton Cache provideOkHttpCache(MyApplication application) { int cacheSize = 10 * 1024 * 1024; // 10 MiB Cache cache = new Cache(application.getCacheDir(), cacheSize); return cache; }
@Provides @Singleton OkHttpClient provideOkHttpClient(Cache cache) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.interceptors().add(logging); return builder.build(); }
public static OkHttpClient getHttpClient() { if (sHttpClient == null) { sHttpClient = new OkHttpClient(); Cache cache = new Cache(Utils.getCacheDir(), 100 * 1024 * 1024); sHttpClient.setCache(cache); sHttpClient.setConnectTimeout(15, TimeUnit.SECONDS); sHttpClient.setReadTimeout(20, TimeUnit.SECONDS); sHttpClient.setWriteTimeout(20, TimeUnit.SECONDS); mGson = new Gson(); } return sHttpClient; }
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; }
public static OkHttpClient getHttpClient(Context context) { if (httpClient == null) { httpClient = new OkHttpClient(); httpClient.setConnectionSpecs(Collections.singletonList(ConnectionSpec.MODERN_TLS)); httpClient.setConnectTimeout(Constants.NETWORK_TIMEOUT_MS, TimeUnit.MILLISECONDS); // Setup cache File cacheDir = new File(context.getCacheDir(), Constants.HTTP_CACHE_NAME); Cache cache = new Cache(cacheDir, Constants.HTTP_CACHE_SIZE); httpClient.setCache(cache); } return httpClient; }
private void ensureCache() { if (useCache && client.getCache() == null) { Cache cache = createCache(getContext()); if (cache != null) { client.setCache(cache); } } }
public static OkHttpClient getUnsafeClient() { OkHttpClient client = new OkHttpClient(); client.setCache(new Cache(LiferayScreensContext.getContext().getCacheDir(), 100000000)); client.setSslSocketFactory(getSslContext().getSocketFactory()); client.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); return client; }
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; }
@Provides @Singleton OkHttpClient provideOkHttpClient(ZippyApplication application) { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(60, TimeUnit.SECONDS); client.setReadTimeout(60, TimeUnit.SECONDS); client.setWriteTimeout(60, TimeUnit.SECONDS); File cacheFile = new File(application.getCacheDir(), "http"); Cache cache = new Cache(cacheFile, CACHE_SIZE); client.setCache(cache); //client.networkInterceptors().add(new StethoInterceptor()); client.networkInterceptors().add(new TimberInterceptor()); client.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); if (response.isSuccessful() && !chain.request().headers("OkHttp-Force-Offline").isEmpty()) { Response.Builder responseBuilder = response.newBuilder(); if (response.header("Cache-Control","no-cache").contains("no-cache")) { responseBuilder.header("Cache-Control", "public, max-age=120"); } if (response.header("Expires").equals("-1")) { responseBuilder.removeHeader("Expires"); } responseBuilder.removeHeader("Pragma"); return responseBuilder.build(); } return response; } }); return client; }
@Provides @Singleton OkHttpClient provideOkHttp(final Cache cache, LoggerInterceptor loggerInterceptor, StethoInterceptor stethoInterceptor) { final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setCache(cache); okHttpClient.networkInterceptors().add(loggerInterceptor); okHttpClient.networkInterceptors().add(stethoInterceptor); okHttpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); okHttpClient.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); okHttpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); return okHttpClient; }
@Provides @Singleton OkHttpClient okHttpClient() { final OkHttpClient client = new OkHttpClient(); // set disk cache client.setCache(new Cache(application.getCacheDir(), DISK_CACHE_SIZE)); // stetho interceptor - only on debug StethoUtil.addStethoInterceptor(client); return client; }
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); }
private void init() { DisplayMetrics dm =getResources().getDisplayMetrics(); SCREEN_WIDTH = Math.min(dm.widthPixels, dm.heightPixels); SCREEN_HEIGHT = Math.max(dm.widthPixels, dm.heightPixels); OkHttpClient client = new OkHttpClient(); File cacheDirectory = new File(Config.CACHE_DIR); if (!cacheDirectory.exists()) { cacheDirectory.mkdirs(); } final Cache cache = new Cache(cacheDirectory, Config.CACHE_SIZE); client.setCache(cache); mRestAdapter = new RestAdapter.Builder() .setEndpoint(Constants.BASE_URL) .setClient(new OkClient(client)) .setRequestInterceptor(new RequestInterceptor() { @Override public void intercept(RequestFacade request) { if (Network.isConnected(getApplicationContext())) { int maxAge = 2; // read from cache for 1 minute request.addHeader( "Cache-Control", "public, max-age=" + maxAge); } else { int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale request.addHeader( "Cache-Control", "public, only-if-cached, max-stale=" + maxStale); } } }) .build(); }
@Provides @Singleton OkHttpClient provideOkHttp(Cache cache) { OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setCache(cache); okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS); return okHttpClient; }
@Inject public DefaultNetworkRequestProvider(@NonNull Context applicationContext) { mOkHttpClient = new OkHttpClient(); mOkHttpClient.setConnectTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); mOkHttpClient.setReadTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); mOkHttpClient.setWriteTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); // Configure a response cache for OkHttp so we get some free bandwidth / battery preservation. File responseCacheDirectory = new File(applicationContext.getCacheDir(), RESPONSE_CACHE_DIRECTORY); mOkHttpClient.setCache(new Cache(responseCacheDirectory, RESPONSE_CACHE_SIZE_MEGABYTES)); mConnectivityManager = (ConnectivityManager) applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE); }
public boolean enableCache( File cacheDirectory, int cacheSize ){ if ( okHttpClient ==null || cacheDirectory == null ){ return false; } Cache cache = new Cache(cacheDirectory, cacheSize); okHttpClient.setCache(cache); return true; }