use of okhttp3.CacheControl in project Atom_Android by Rogrand-Dev.
the class HttpModule method provideClient.
@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
if (DemoApp.getAppContext().isDebug()) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
LogUtils.i(TAG, message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// 设置 Log 拦截器
builder.addInterceptor(loggingInterceptor);
}
File cacheFile = new File(DataUtils.getCacheFile(DemoApp.getAppContext()), "RograndCache");
// 100 MB
int cacheSize = 100 * 1024 * 1024;
Cache cache = new Cache(cacheFile, cacheSize);
Interceptor cacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
CacheControl.Builder cacheBuilder = new CacheControl.Builder();
cacheBuilder.maxAge(0, TimeUnit.SECONDS);
cacheBuilder.maxStale(365, TimeUnit.DAYS);
CacheControl cacheControl = cacheBuilder.build();
Request request = chain.request();
if (!NetUtils.isNetworkAvailable(DemoApp.getAppContext())) {
request = request.newBuilder().cacheControl(cacheControl).build();
}
Response response = chain.proceed(request);
if (NetUtils.isNetworkAvailable(DemoApp.getAppContext())) {
// 有网络时, 不缓存, 最大保存时长为0
int maxAge = 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;
}
};
// 设置 header(设置 Token、API 版本号)
Interceptor headerInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder().addHeader("Authorization", "Bearer " + SPUtils.get(DemoApp.getAppContext(), Constants.ACCESS_TOKEN, "")).addHeader("api_version", UrlConstants.API_VERSION).build();
return chain.proceed(request);
}
};
// 设置统一的请求头部参数
builder.addInterceptor(headerInterceptor);
// 设置缓存
builder.addNetworkInterceptor(cacheInterceptor);
builder.addInterceptor(cacheInterceptor);
builder.cache(cache);
// 设置连接超时
builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
// 设置读取数据超时
builder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
// 设置写入数据超时
builder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
// 设置 Stetho
builder.addNetworkInterceptor(new StethoInterceptor());
// 设置 Cookie
builder.cookieJar(new CookieManger(DemoApp.getAppContext()));
// 错误重连
builder.retryOnConnectionFailure(true);
return builder.build();
}
use of okhttp3.CacheControl in project Signal-Android by WhisperSystems.
the class ChunkedDataFetcher method makeChunkRequest.
private CallRequestController makeChunkRequest(@NonNull OkHttpClient client, @NonNull String url, @NonNull ByteRange range) {
Request request = new Request.Builder().url(url).cacheControl(NO_CACHE).addHeader("Range", "bytes=" + range.start + "-" + range.end).addHeader("Accept-Encoding", "identity").build();
Call call = client.newCall(request);
CallRequestController callController = new CallRequestController(call);
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
callController.cancel();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
if (!response.isSuccessful()) {
callController.cancel();
if (response.body() != null)
response.body().close();
return;
}
if (response.body() == null) {
callController.cancel();
if (response.body() != null)
response.body().close();
return;
}
InputStream stream = new SkippingInputStream(ContentLengthInputStream.obtain(response.body().byteStream(), response.body().contentLength()), range.ignoreFirst);
callController.setStream(stream);
}
});
return callController;
}
use of okhttp3.CacheControl in project Signal-Android by WhisperSystems.
the class ChunkedDataFetcher method fetchChunksWithUnknownTotalSize.
private RequestController fetchChunksWithUnknownTotalSize(@NonNull String url, @NonNull Callback callback) {
CompositeRequestController compositeController = new CompositeRequestController();
long chunkSize = new SecureRandom().nextInt(1024) + 1024;
Request request = new Request.Builder().url(url).cacheControl(NO_CACHE).addHeader("Range", "bytes=0-" + (chunkSize - 1)).addHeader("Accept-Encoding", "identity").build();
Call firstChunkCall = client.newCall(request);
compositeController.addController(new CallRequestController(firstChunkCall));
firstChunkCall.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
if (!compositeController.isCanceled()) {
callback.onFailure(e);
compositeController.cancel();
}
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
String contentRange = response.header("Content-Range");
if (!response.isSuccessful()) {
Log.w(TAG, "Non-successful response code: " + response.code());
callback.onFailure(new IOException("Non-successful response code: " + response.code()));
compositeController.cancel();
if (response.body() != null)
response.body().close();
return;
}
if (TextUtils.isEmpty(contentRange)) {
Log.w(TAG, "Missing Content-Range header.");
callback.onFailure(new IOException("Missing Content-Length header."));
compositeController.cancel();
if (response.body() != null)
response.body().close();
return;
}
if (response.body() == null) {
Log.w(TAG, "Missing body.");
callback.onFailure(new IOException("Missing body on initial request."));
compositeController.cancel();
return;
}
Optional<Long> contentLength = parseLengthFromContentRange(contentRange);
if (!contentLength.isPresent()) {
Log.w(TAG, "Unable to parse length from Content-Range.");
callback.onFailure(new IOException("Unable to get parse length from Content-Range."));
compositeController.cancel();
return;
}
if (chunkSize >= contentLength.get()) {
try {
callback.onSuccess(response.body().byteStream());
} catch (IOException e) {
callback.onFailure(e);
compositeController.cancel();
}
} else {
InputStream stream = ContentLengthInputStream.obtain(response.body().byteStream(), chunkSize);
fetchChunks(url, contentLength.get(), Optional.of(new Pair<>(stream, chunkSize)), compositeController, callback);
}
}
});
return compositeController;
}
use of okhttp3.CacheControl in project Signal-Android by WhisperSystems.
the class LinkPreviewRepository method fetchMetadata.
@NonNull
private RequestController fetchMetadata(@NonNull String url, Consumer<Metadata> callback) {
Call call = client.newCall(new Request.Builder().url(url).cacheControl(NO_CACHE).build());
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.w(TAG, "Request failed.", e);
callback.accept(Metadata.empty());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
if (!response.isSuccessful()) {
Log.w(TAG, "Non-successful response. Code: " + response.code());
callback.accept(Metadata.empty());
return;
} else if (response.body() == null) {
Log.w(TAG, "No response body.");
callback.accept(Metadata.empty());
return;
}
String body = OkHttpUtil.readAsString(response.body(), FAILSAFE_MAX_TEXT_SIZE);
OpenGraph openGraph = LinkPreviewUtil.parseOpenGraphFields(body);
Optional<String> title = openGraph.getTitle();
Optional<String> description = openGraph.getDescription();
Optional<String> imageUrl = openGraph.getImageUrl();
long date = openGraph.getDate();
if (imageUrl.isPresent() && !LinkPreviewUtil.isValidPreviewUrl(imageUrl.get())) {
Log.i(TAG, "Image URL was invalid or for a non-whitelisted domain. Skipping.");
imageUrl = Optional.absent();
}
callback.accept(new Metadata(title, description, date, imageUrl));
}
});
return new CallRequestController(call);
}
Aggregations