use of okhttp3.CacheControl in project BaseProject by wareine.
the class CacheInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// 没网络的情况强制读取缓存(必须判断,避免断网情况下获取不到缓存)
if (!NetworkUtils.isConnected()) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
Response response = chain.proceed(request);
if (NetworkUtils.isConnected()) {
// 在有网络的情况下,缓存失效的时间为60秒
int maxAge = 60;
return response.newBuilder().removeHeader("Pragma").header("Cache-Control", "public, max-age=" + maxAge).build();
} else {
// 没有网络的情况下,缓存失效的时间为4周
int maxStale = 60 * 60 * 24 * 28;
return response.newBuilder().removeHeader("Pragma").header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).build();
}
}
use of okhttp3.CacheControl in project yandex-money-sdk-java by yandex-money.
the class DefaultApiClient method prepareRequest.
private Request prepareRequest(ApiRequest<?> request) {
checkNotNull(request, "request");
Request.Builder builder = new Request.Builder().cacheControl(cacheControl).url(request.requestUrl(getHostsProvider())).addHeader(HttpHeaders.USER_AGENT, getUserAgent().getName()).addHeader(HttpHeaders.ACCEPT_LANGUAGE, getLanguage().iso6391Code);
if (isAuthorized()) {
builder.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
}
for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
String value = entry.getValue();
if (value != null) {
builder.addHeader(entry.getKey(), value);
}
}
ApiRequest.Method method = request.getMethod();
if (method != ApiRequest.Method.GET) {
RequestBody body = RequestBody.create(MediaType.parse(request.getContentType()), request.getBody());
switch(method) {
case POST:
builder.post(body);
break;
case PUT:
builder.put(body);
break;
case DELETE:
builder.delete();
break;
}
}
return builder.build();
}
use of okhttp3.CacheControl in project LibreraReader by foobnix.
the class OPDS method getHttpResponse.
public static String getHttpResponse(String url) throws IOException {
Request request = //
new Request.Builder().header("User-Agent", USER_AGENT).cacheControl(//
new CacheControl.Builder().maxAge(10, //
TimeUnit.MINUTES).build()).url(//
url).build();
Response response = //
client.newCall(//
request).execute();
LOG.d("Header: >>", url);
LOG.d("Header: Status code:", response.code());
for (int i = 0; i < response.headers().size(); i++) {
String name = response.headers().name(i);
String value = response.headers().value(i);
LOG.d("Header: ", name, value);
}
if (response.code() == 401 && TxtUtils.isEmpty(TempHolder.get().login)) {
return CODE_401;
} else {
Credentials credentials = new Credentials(TempHolder.get().login, TempHolder.get().password);
final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(credentials);
final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
DispatchingAuthenticator authenticator = //
new DispatchingAuthenticator.Builder().with("digest", //
digestAuthenticator).with("basic", //
basicAuthenticator).build();
client = //
builder.authenticator(//
new CachingAuthenticatorDecorator(authenticator, authCache)).addInterceptor(//
new AuthenticationCacheInterceptor(authCache)).build();
response = client.newCall(request).execute();
if (response.code() == 401) {
return CODE_401;
}
}
String string = response.body().string();
return string;
}
use of okhttp3.CacheControl in project GeekNews by codeestX.
the class HttpModule method provideClient.
@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(loggingInterceptor);
}
File cacheFile = new File(Constants.PATH_CACHE);
Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
Interceptor cacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!SystemUtil.isNetworkConnected()) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
Response response = chain.proceed(request);
if (SystemUtil.isNetworkConnected()) {
int maxAge = 0;
// 有网络时, 不缓存, 最大保存时长为0
response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
} else {
// 无网络时,设置超时为4周
int maxStale = 60 * 60 * 24 * 28;
response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
}
return response;
}
};
// Interceptor apikey = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// request = request.newBuilder()
// .addHeader("apikey",Constants.KEY_API)
// .build();
// return chain.proceed(request);
// }
// }
// 设置统一的请求头部参数
// builder.addInterceptor(apikey);
// 设置缓存
builder.addNetworkInterceptor(cacheInterceptor);
builder.addInterceptor(cacheInterceptor);
builder.cache(cache);
// 设置超时
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
// 错误重连
builder.retryOnConnectionFailure(true);
return builder.build();
}
use of okhttp3.CacheControl in project smartmodule by carozhu.
the class OkHttpUtils method getInstance.
public static OkHttpClient.Builder getInstance(final Context context) {
if (singleton == null) {
synchronized (OkHttpUtils.class) {
if (singleton == null) {
singleton = new OkHttpClient().newBuilder();
singleton.connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS);
singleton.readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS);
// okhttp设置错误重新连接
singleton.retryOnConnectionFailure(true);
// singleton.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR);
// singleton.addInterceptor(REWRITE_RESPONSE_INTERCEPTOR_OFFLINE);
File cacheDir = new File(context.getCacheDir(), RESPONSE_CACHE);
singleton.cache(new Cache(cacheDir, RESPONSE_CACHE_SIZE));
if (ConfigureManager.getConfigureManager().isOkhttpLogger()) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
singleton.addInterceptor(interceptor);
}
if (ConfigureManager.getConfigureManager().isOkhttpCache()) {
// 设置缓存路径
File httpCacheDirectory = new File(context.getCacheDir(), "httpCacheResponses");
// 设置缓存 100M
Cache cache = new Cache(httpCacheDirectory, RESPONSE_CACHE_SIZE);
Interceptor myinterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.i(TAG, "request=" + request);
if (!NetworkUtil.isNetworkAvailable(context)) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
Log.i(TAG, "no network");
}
Response response = chain.proceed(request);
if (NetworkUtil.isNetworkAvailable(context)) {
// 有网络时 设置缓存超时时间0个小时
int maxAge = 0 * 60;
Log.i(TAG, "has network maxAge=" + maxAge);
response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader(// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
"Pragma").build();
} else {
Log.i(TAG, "network error");
// 无网络时,设置超时为4周
int maxStale = 60 * 60 * 24 * 28;
Log.i(TAG, "has maxStale=" + maxStale);
response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
Log.i(TAG, "response build maxStale=" + maxStale);
}
return response;
}
};
singleton.addInterceptor(myinterceptor).cache(cache);
}
}
}
}
return singleton;
}
Aggregations