Search in sources :

Example 26 with CacheControl

use of okhttp3.CacheControl in project Awesome-WanAndroid by JsonChao.

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 = chain -> {
        Request request = chain.request();
        if (!CommonUtils.isNetworkConnected()) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }
        Response response = chain.proceed(request);
        if (CommonUtils.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;
    };
    // 设置缓存
    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);
    // cookie认证
    builder.cookieJar(new CookiesManager());
    return builder.build();
}
Also used : Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) Cache(okhttp3.Cache) GeeksApis(json.chao.com.wanandroid.core.http.api.GeeksApis) CacheControl(okhttp3.CacheControl) Singleton(javax.inject.Singleton) File(java.io.File) WanAndroidUrl(json.chao.com.wanandroid.di.qualifier.WanAndroidUrl) Retrofit(retrofit2.Retrofit) RxJava2CallAdapterFactory(retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory) CommonUtils(json.chao.com.wanandroid.utils.CommonUtils) TimeUnit(java.util.concurrent.TimeUnit) Constants(json.chao.com.wanandroid.app.Constants) Module(dagger.Module) OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) BuildConfig(json.chao.com.wanandroid.BuildConfig) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) Response(okhttp3.Response) CookiesManager(json.chao.com.wanandroid.core.http.cookies.CookiesManager) Provides(dagger.Provides) Response(okhttp3.Response) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) CookiesManager(json.chao.com.wanandroid.core.http.cookies.CookiesManager) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 27 with CacheControl

use of okhttp3.CacheControl in project Ency by xiarunhao123.

the class HttpModule method provideOkHttpClient.

@Provides
@Singleton
OkHttpClient provideOkHttpClient(OkHttpClient.Builder builder, final Context context) {
    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 (!AppNetWorkUtil.isNetworkConnected(context)) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }
            Response response = chain.proceed(request);
            if (AppNetWorkUtil.isNetworkConnected(context)) {
                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;
        }
    };
    // 设置缓存
    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();
}
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 28 with CacheControl

use of okhttp3.CacheControl in project BaseProject by fly803.

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();
    }
    okhttp3.Response response = chain.proceed(request);
    if (NetworkUtils.isConnected()) {
        // 有网络情况下,根据请求接口的设置,配置缓存。
        // 这样在下次请求时,根据缓存决定是否真正发出请求。
        String cacheControl = request.cacheControl().toString();
        // 当然如果你想在有网络的情况下都直接走网络,那么只需要
        // 将其超时时间这是为0即可:String cacheControl="Cache-Control:public,max-age=0"
        // read from cache for 1 minute
        int maxAge = 60 * 60;
        return response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
    } else {
        // 无网络
        // tolerate 4-weeks stale
        int maxStale = 60 * 60 * 24 * 28;
        return response.newBuilder().header("Cache-Control", "public,only-if-cached,max-stale=" + maxStale).removeHeader("Pragma").build();
    }
}
Also used : Request(okhttp3.Request) Response(okhttp3.Response)

Example 29 with CacheControl

use of okhttp3.CacheControl in project LibreraReader by foobnix.

the class OpdsFragment2 method onClickLink.

public void onClickLink(final Link link) {
    LOG.d("onClickLink", link.type, link.href);
    if (link.filePath != null) {
        FileMeta meta = new FileMeta(link.filePath);
        meta.setTitle(link.getDownloadName());
        ExtUtils.openFile(getActivity(), meta);
    } else if (link.isDisabled()) {
        Toast.makeText(getActivity(), R.string.can_t_download, Toast.LENGTH_SHORT).show();
    } else if (link.isWebLink()) {
        Urls.open(getActivity(), link.href);
    } else if (link.isOpdsLink()) {
        if (url.equals("/")) {
            urlRoot = link.href;
        }
        url = link.href;
        stack.push(url);
        LOG.d("URLAction", "ADD", url);
        populate();
    } else if (link.isImageLink()) {
    } else {
        LOG.d("Download >>", link.href);
        if (isInProgress()) {
            Toast.makeText(getContext(), R.string.please_wait, Toast.LENGTH_SHORT).show();
            return;
        }
        AlertDialogs.showDialog(getActivity(), link.getDownloadName(), getActivity().getString(R.string.download), new Runnable() {

            String bookPath;

            @Override
            public void run() {
                new AsyncTask() {

                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    protected Object doInBackground(Object... params) {
                        try {
                            OutputStream outStream = null;
                            String displayName = link.getDownloadName();
                            if (ExtUtils.isExteralSD(AppState.get().downlodsPath)) {
                                String mimeType = ExtUtils.getMimeType(displayName);
                                Uri uri = Uri.parse(AppState.get().downlodsPath);
                                Uri childrenUri = ExtUtils.getChildUri(getContext(), uri);
                                Uri createDocument = DocumentsContract.createDocument(getActivity().getContentResolver(), childrenUri, mimeType, displayName);
                                bookPath = createDocument.toString();
                                outStream = getActivity().getContentResolver().openOutputStream(createDocument);
                            } else {
                                File LIRBI_DOWNLOAD_DIR = new File(AppState.get().downlodsPath);
                                if (!LIRBI_DOWNLOAD_DIR.exists()) {
                                    LIRBI_DOWNLOAD_DIR.mkdirs();
                                }
                                final File file = new File(LIRBI_DOWNLOAD_DIR, displayName);
                                file.delete();
                                outStream = new FileOutputStream(file);
                                bookPath = file.getPath();
                            }
                            okhttp3.Request request = // 
                            new okhttp3.Request.Builder().cacheControl(new CacheControl.Builder().noCache().build()).url(// 
                            link.href).build();
                            Response response = // 
                            OPDS.client.newCall(// 
                            request).execute();
                            BufferedSource source = response.body().source();
                            BufferedSink sink = Okio.buffer(Okio.sink(outStream));
                            sink.writeAll(response.body().source());
                            sink.close();
                        } catch (Exception e) {
                            LOG.e(e);
                            return false;
                        }
                        return true;
                    }

                    @Override
                    protected void onPreExecute() {
                        progressBar.setVisibility(View.VISIBLE);
                    }

                    @Override
                    protected void onPostExecute(Object result) {
                        progressBar.setVisibility(View.GONE);
                        if ((Boolean) result == false) {
                            Toast.makeText(getContext(), R.string.loading_error, Toast.LENGTH_LONG).show();
                        // Urls.openWevView(getActivity(), link.href, null);
                        } else {
                            link.filePath = bookPath;
                            if (!ExtUtils.isExteralSD(bookPath)) {
                                FileMeta meta = AppDB.get().getOrCreate(bookPath);
                                meta.setIsSearchBook(true);
                                AppDB.get().updateOrSave(meta);
                                IMG.loadCoverPageWithEffect(meta.getPath(), IMG.getImageSize());
                            }
                            TempHolder.listHash++;
                        }
                        clearEmpty();
                    }
                }.execute();
            }
        });
    }
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) AsyncTask(android.os.AsyncTask) BufferedSink(okio.BufferedSink) Uri(android.net.Uri) ResultResponse(com.foobnix.android.utils.ResultResponse) Response(okhttp3.Response) FileOutputStream(java.io.FileOutputStream) CacheControl(okhttp3.CacheControl) File(java.io.File) FileMeta(com.foobnix.dao2.FileMeta) BufferedSource(okio.BufferedSource)

Example 30 with CacheControl

use of okhttp3.CacheControl in project LibreraReader by foobnix.

the class FontExtractor method showDownloadFontsDialog.

public static void showDownloadFontsDialog(final Activity a, final View label1, final View label2) {
    AlertDialogs.showDialog(a, a.getString(R.string.do_you_want_to_download_more_book_fonts_10mb_), a.getString(R.string.download), new Runnable() {

        @Override
        public void run() {
            new AsyncTask() {

                ProgressDialog progressDialog;

                @Override
                protected void onPreExecute() {
                    progressDialog = ProgressDialog.show(a, "", a.getString(R.string.please_wait));
                }

                @Override
                protected Object doInBackground(Object... params) {
                    try {
                        downloadFontFile(FONT_HTTP_ZIP1);
                    } catch (Exception e) {
                        LOG.e(e);
                    }
                    if (!hasZipFonts()) {
                        try {
                            downloadFontFile(FONT_HTTP_ZIP2);
                        } catch (Exception e) {
                            LOG.e(e);
                        }
                    }
                    if (hasZipFonts()) {
                        copyFontsFromZip();
                        return true;
                    }
                    return null;
                }

                private void downloadFontFile(String url) throws IOException, FileNotFoundException {
                    LOG.d("Download from", url);
                    LOG.d("Download to  ", FONT_LOCAL_ZIP);
                    FONT_LOCAL_ZIP.delete();
                    okhttp3.Request request = // 
                    new okhttp3.Request.Builder().cacheControl(new CacheControl.Builder().noCache().build()).url(// 
                    url).build();
                    Response response = // 
                    OPDS.client.newCall(// 
                    request).execute();
                    BufferedSource source = response.body().source();
                    FileOutputStream out = new FileOutputStream(FONT_LOCAL_ZIP);
                    BufferedSink sink = Okio.buffer(Okio.sink(out));
                    sink.writeAll(response.body().source());
                    sink.close();
                    out.close();
                }

                @Override
                protected void onPostExecute(Object result) {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    if (result == null) {
                        Toast.makeText(a, R.string.msg_unexpected_error, Toast.LENGTH_LONG).show();
                    }
                    label1.setVisibility(FontExtractor.hasZipFonts() ? View.GONE : View.VISIBLE);
                    if (hasZipFonts() && label2 != null) {
                        label2.performClick();
                    }
                }
            }.execute();
        }
    });
}
Also used : AsyncTask(android.os.AsyncTask) BufferedSink(okio.BufferedSink) ProgressDialog(android.app.ProgressDialog) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Response(okhttp3.Response) FileOutputStream(java.io.FileOutputStream) CacheControl(okhttp3.CacheControl) BufferedSource(okio.BufferedSource)

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