Search in sources :

Example 16 with CacheControl

use of okhttp3.CacheControl in project AntennaPod by AntennaPod.

the class ItunesTopListLoader method getTopListFeed.

private String getTopListFeed(OkHttpClient client, String country, int limit) throws IOException {
    String url = "https://itunes.apple.com/%s/rss/toppodcasts/limit=" + limit + "/explicit=true/json";
    Log.d(TAG, "Feed URL " + String.format(url, country));
    Request.Builder httpReq = new Request.Builder().cacheControl(new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build()).url(String.format(url, country));
    try (Response response = client.newCall(httpReq.build()).execute()) {
        if (response.isSuccessful()) {
            return response.body().string();
        }
        if (response.code() == 400) {
            throw new IOException("iTunes does not have data for the selected country.");
        }
        String prefix = context.getString(R.string.error_msg_prefix);
        throw new IOException(prefix + response);
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException)

Example 17 with CacheControl

use of okhttp3.CacheControl in project ExoPlayer by google.

the class OkHttpDataSource method makeRequest.

/**
 * Establishes a connection.
 */
private Request makeRequest(DataSpec dataSpec) throws HttpDataSourceException {
    long position = dataSpec.position;
    long length = dataSpec.length;
    @Nullable HttpUrl url = HttpUrl.parse(dataSpec.uri.toString());
    if (url == null) {
        throw new HttpDataSourceException("Malformed URL", dataSpec, PlaybackException.ERROR_CODE_FAILED_RUNTIME_CHECK, HttpDataSourceException.TYPE_OPEN);
    }
    Request.Builder builder = new Request.Builder().url(url);
    if (cacheControl != null) {
        builder.cacheControl(cacheControl);
    }
    Map<String, String> headers = new HashMap<>();
    if (defaultRequestProperties != null) {
        headers.putAll(defaultRequestProperties.getSnapshot());
    }
    headers.putAll(requestProperties.getSnapshot());
    headers.putAll(dataSpec.httpRequestHeaders);
    for (Map.Entry<String, String> header : headers.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    @Nullable String rangeHeader = buildRangeRequestHeader(position, length);
    if (rangeHeader != null) {
        builder.addHeader(HttpHeaders.RANGE, rangeHeader);
    }
    if (userAgent != null) {
        builder.addHeader(HttpHeaders.USER_AGENT, userAgent);
    }
    if (!dataSpec.isFlagSet(DataSpec.FLAG_ALLOW_GZIP)) {
        builder.addHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
    }
    @Nullable RequestBody requestBody = null;
    if (dataSpec.httpBody != null) {
        requestBody = RequestBody.create(null, dataSpec.httpBody);
    } else if (dataSpec.httpMethod == DataSpec.HTTP_METHOD_POST) {
        // OkHttp requires a non-null body for POST requests.
        requestBody = RequestBody.create(null, Util.EMPTY_BYTE_ARRAY);
    }
    builder.method(dataSpec.getHttpMethodString(), requestBody);
    return builder.build();
}
Also used : HashMap(java.util.HashMap) Request(okhttp3.Request) HashMap(java.util.HashMap) Map(java.util.Map) Nullable(androidx.annotation.Nullable) HttpUrl(okhttp3.HttpUrl) RequestBody(okhttp3.RequestBody)

Example 18 with CacheControl

use of okhttp3.CacheControl in project picasso by square.

the class NetworkRequestHandler method createRequest.

private static okhttp3.Request createRequest(Request request) {
    CacheControl cacheControl = null;
    int networkPolicy = request.networkPolicy;
    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();
        }
    }
    Uri uri = checkNotNull(request.uri, "request.uri == null");
    okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(uri.toString());
    if (cacheControl != null) {
        builder.cacheControl(cacheControl);
    }
    return builder.build();
}
Also used : CacheControl(okhttp3.CacheControl) Uri(android.net.Uri)

Example 19 with CacheControl

use of okhttp3.CacheControl in project Gradle-demo by Arisono.

the class CacheInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    switch(cacheType) {
        case CacheType.ONLY_NETWORK:
            OkhttpUtils.println("强制使用网络");
            request = request.newBuilder().cacheControl(// 只访问網絡
            CacheControl.FORCE_NETWORK).build();
            break;
        case CacheType.ONLY_CACHED:
            OkhttpUtils.println("强制使用缓存");
            request = request.newBuilder().cacheControl(// 只访问缓存
            CacheControl.FORCE_CACHE).build();
            break;
        default:
            break;
    }
    Response response = chain.proceed(request);
    Response response1 = response.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "max-age=" + cacheTime).build();
    return response1;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request)

Example 20 with CacheControl

use of okhttp3.CacheControl in project SeeWeather by xcc3641.

the class RetrofitSingleton method initOkHttp.

private static void initOkHttp() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // 缓存 http://www.jianshu.com/p/93153b34310e
    File cacheFile = new File(C.NET_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = chain -> {
        Request request = chain.request();
        if (!Util.isNetworkConnected(BaseApplication.getAppContext())) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }
        Response response = chain.proceed(request);
        Response.Builder newBuilder = response.newBuilder();
        if (Util.isNetworkConnected(BaseApplication.getAppContext())) {
            int maxAge = 0;
            // 有网络时 设置缓存超时时间0个小时
            newBuilder.header("Cache-Control", "public, max-age=" + maxAge);
        } else {
            // 无网络时,设置超时为4周
            int maxStale = 60 * 60 * 24 * 28;
            newBuilder.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale);
        }
        return newBuilder.build();
    };
    builder.cache(cache).addInterceptor(cacheInterceptor);
    if (BuildConfig.DEBUG) {
        builder.addNetworkInterceptor(new StethoInterceptor());
    }
    // 设置超时
    builder.connectTimeout(15, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    // 错误重连
    builder.retryOnConnectionFailure(true);
    sOkHttpClient = builder.build();
}
Also used : StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) Cache(okhttp3.Cache) BaseApplication(com.xiecc.seeWeather.base.BaseApplication) C(com.xiecc.seeWeather.common.C) CacheControl(okhttp3.CacheControl) Consumer(io.reactivex.functions.Consumer) CityORM(com.xiecc.seeWeather.modules.main.domain.CityORM) File(java.io.File) Retrofit(retrofit2.Retrofit) RxJava2CallAdapterFactory(retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory) BuildConfig(com.xiecc.seeWeather.BuildConfig) TimeUnit(java.util.concurrent.TimeUnit) ToastUtil(com.xiecc.seeWeather.common.utils.ToastUtil) OkHttpClient(okhttp3.OkHttpClient) Util(com.xiecc.seeWeather.common.utils.Util) RxUtil(com.xiecc.seeWeather.common.utils.RxUtil) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) Version(com.xiecc.seeWeather.modules.about.domain.Version) Response(okhttp3.Response) Observable(io.reactivex.Observable) WhereBuilder(com.litesuits.orm.db.assit.WhereBuilder) Weather(com.xiecc.seeWeather.modules.main.domain.Weather) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) WhereBuilder(com.litesuits.orm.db.assit.WhereBuilder) Request(okhttp3.Request) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) File(java.io.File) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) Cache(okhttp3.Cache)

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