下面列出了怎么用com.squareup.okhttp.Cache的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
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);
}
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);
}
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;
}
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);
}
@Provides
@Singleton
OkHttpClient provideOkHttp(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(cache);
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
return okHttpClient;
}
private Cache createOkHttpCache() {
try {
File directory = new File(mContext.getCacheDir(), "ok-http");
return new Cache(directory, 3000000);
} catch (IOException e) {
return null;
}
}
@Provides
@Singleton
OkHttpClient provideOkHttp(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setCache(cache);
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
return okHttpClient;
}
private void ensureCache() {
if (useCache && client.getCache() == null) {
Cache cache = createCache(getContext());
if (cache != null) {
client.setCache(cache);
}
}
}
/**
* 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);
}
}
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;
}
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 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);
}
}
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);
}
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;
}
@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;
}
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());
}
}
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);
}
}
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);
}
public void setCache (File cacheDirectory, long maxCacheSize) {
Cache cache = (new Cache(cacheDirectory, maxCacheSize));
client.setCache(cache);
}
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache) {
return getHttpURLConnection(url, cache, null);
}
public static Cache getCache(final File cacheDir, final int maxSize) throws IOException {
return new Cache(cacheDir, maxSize);
}
private OkHttpConnector createCachedHttpConnector() {
final File cacheDirectory = getCacheDirectory();
final Cache cache = new Cache(cacheDirectory, this.cacheSize);
return new OkHttpConnector(new OkUrlFactory(new OkHttpClient().setCache(cache)));
}