Search in sources :

Example 36 with CacheControl

use of okhttp3.CacheControl in project apps-android-wikipedia by wikimedia.

the class DefaultMaxStaleRequestInterceptor method intercept.

@Override
public Response intercept(@NonNull Chain chain) throws IOException {
    Request req = chain.request();
    int maxStaleSeconds = req.cacheControl().maxStaleSeconds() < 0 ? Integer.MAX_VALUE : req.cacheControl().maxStaleSeconds();
    String cacheControl = CacheControlUtil.replaceMaxStale(req.cacheControl().toString(), maxStaleSeconds);
    req = req.newBuilder().header("Cache-Control", cacheControl).build();
    return chain.proceed(req);
}
Also used : Request(okhttp3.Request)

Example 37 with CacheControl

use of okhttp3.CacheControl in project Qblog_Android by qiaoyhh.

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);
    // }
    // 日志显示级别
    HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
    // 新建log拦截器
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

        @Override
        public void log(String message) {
            Logger.e("okhttp  URL====" + message);
        }
    });
    loggingInterceptor.setLevel(level);
    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();
                Logger.e("无网络=======" + response.toString());
            }
            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.addInterceptor(loggingInterceptor);
    // 设置缓存
    builder.addNetworkInterceptor(cacheInterceptor);
    builder.addInterceptor(cacheInterceptor);
    builder.cache(cache);
    // 设置超时
    builder.connectTimeout(15, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    // 错误重连
    builder.retryOnConnectionFailure(true);
    return builder.build();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 38 with CacheControl

use of okhttp3.CacheControl in project TicktockMusic by Lauzy.

the class CacheInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (!isNetworkConnected()) {
        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
    }
    /*else if (isNetworkConnected()) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();
        }*/
    Response response = chain.proceed(request);
    if (isNetworkConnected()) {
        // 1分钟内不再访问服务器
        int maxCacheTime = 60 * 60;
        response = response.newBuilder().header("Cache-Control", "public, max-age=" + maxCacheTime).removeHeader("Pragma").build();
    } else {
        // 5天
        int maxStale = 60 * 60 * 24 * 5;
        response = response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
    }
    return response;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) SuppressLint(android.annotation.SuppressLint)

Example 39 with CacheControl

use of okhttp3.CacheControl in project HL4A by HL4A.

the class 连接 method 同步.

public 资源 同步() {
    try {
        if (!Cookie表.isEmpty()) {
            请求头("Cookie", 转换Cookie(Cookie表));
        }
        请求.headers(请求头.build());
        请求.cacheControl(new CacheControl.Builder().noCache().build());
        ByteArrayOutputStream $输出 = 流.输出.字节();
        if (JSON输出) {
            if (JSON == null && 参数表.长度() > 0) {
                JSON(参数表);
            }
            if (JSON != null) {
                $输出.write(JSON.getBytes());
            }
        } else {
            byte[] $分隔 = ("--" + 标识).getBytes();
            byte[] $换行 = "\r\n".getBytes();
            if (!参数表.isEmpty()) {
                for (Map.Entry<String, String> $单个 : 参数表.entrySet()) {
                    $输出.write($换行);
                    $输出.write($分隔);
                    $输出.write($换行);
                    $输出.write("Content-Disposition: form-data;".getBytes());
                    $输出.write(("name=\"" + 编码($单个.getKey()) + "\"").getBytes());
                    $输出.write($换行);
                    $输出.write(编码($单个.getValue()).getBytes());
                }
            }
            if (!文件表.isEmpty()) {
                for (Map.Entry<String, File> $单个 : 文件表.entrySet()) {
                    File $文件 = $单个.getValue();
                    $输出.write($换行);
                    $输出.write($分隔);
                    $输出.write($换行);
                    $输出.write("Content-Disposition: form-data;".getBytes());
                    $输出.write(("name=\"" + 编码($单个.getKey()) + "\";").getBytes());
                    $输出.write(("filename=\"" + 编码($文件.getName()) + "\";").getBytes());
                    $输出.write($换行);
                    流.保存($输出, 流.输入.文件($文件.getPath()));
                }
            }
            $输出.write($换行);
            $输出.write($分隔);
            $输出.write("--".getBytes());
        }
        $输出.flush();
        请求.method(模式, ("GET".equals(模式) || "HEAD".equals(模式)) ? null : RequestBody.create(类型, $输出.toByteArray()));
        Request $请求 = 请求.build();
        return new 资源(网络实例.newCall($请求).execute());
    } catch (Exception $错误) {
    }
    return new 资源(null);
}
Also used : Request(okhttp3.Request) CacheControl(okhttp3.CacheControl) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Map(java.util.Map) File(java.io.File) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException)

Example 40 with CacheControl

use of okhttp3.CacheControl in project SeriesGuide by UweTrottmann.

the class SgPicassoRequestHandler method createRequest.

private static okhttp3.Request createRequest(Uri uri, int networkPolicy) {
    CacheControl cacheControl = null;
    if (networkPolicy != 0) {
        if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
            cacheControl = CacheControl.FORCE_CACHE;
        } else {
            CacheControl.Builder builder = new CacheControl.Builder();
            if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
                builder.noCache();
            }
            if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
                builder.noStore();
            }
            cacheControl = builder.build();
        }
    }
    okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(uri.toString());
    if (cacheControl != null) {
        builder.cacheControl(cacheControl);
    }
    return builder.build();
}
Also used : Request(com.squareup.picasso.Request) CacheControl(okhttp3.CacheControl)

Aggregations

Request (okhttp3.Request)33 Response (okhttp3.Response)28 CacheControl (okhttp3.CacheControl)15 IOException (java.io.IOException)11 File (java.io.File)10 Interceptor (okhttp3.Interceptor)9 Cache (okhttp3.Cache)8 OkHttpClient (okhttp3.OkHttpClient)6 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)6 Provides (dagger.Provides)4 Singleton (javax.inject.Singleton)4 Call (okhttp3.Call)4 RequestBody (okhttp3.RequestBody)4 Uri (android.net.Uri)3 Map (java.util.Map)3 AsyncTask (android.os.AsyncTask)2 ContentLengthInputStream (com.bumptech.glide.util.ContentLengthInputStream)2 StethoInterceptor (com.facebook.stetho.okhttp3.StethoInterceptor)2 ProgressRequestBody (io.chelizi.amokhttp.upload.ProgressRequestBody)2 FileOutputStream (java.io.FileOutputStream)2