Search in sources :

Example 6 with CacheControl

use of okhttp3.CacheControl in project instructure-android by instructure.

the class MobileVerifyAPI method getAuthenticationRetrofit.

private static Retrofit getAuthenticationRetrofit() {
    final String userAgent = ApiPrefs.getUserAgent();
    OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (!userAgent.equals("")) {
                Request request = chain.request().newBuilder().header("User-Agent", userAgent).cacheControl(CacheControl.FORCE_NETWORK).build();
                return chain.proceed(request);
            } else {
                return chain.proceed(chain.request());
            }
        }
    }).build();
    return new Retrofit.Builder().baseUrl("https://canvas.instructure.com/api/v1/").client(httpClient).addConverterFactory(GsonConverterFactory.create()).build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Interceptor(okhttp3.Interceptor)

Example 7 with CacheControl

use of okhttp3.CacheControl in project amhttp by Eddieyuan123.

the class RequestManager method post.

public <T> void post(Context context, String url, CacheControl cacheControl, HashMap<String, String> headers, String params, Object tag, int callMethod, final OnAddListener<T> listener) {
    try {
        IRequestBodyFactory requestBodyFactory = new RequestBodyFactoryImpl();
        RequestBody requestBody = requestBodyFactory.buildRequestBody(params);
        final Request request = new Request.Builder().cacheControl(cacheControl == null ? CacheControl.FORCE_NETWORK : cacheControl).tag(tag == null ? context.hashCode() : tag).headers(Headers.of(headers)).url(url).post(requestBody).build();
        if (callMethod == CallMethod.SYNC) {
            RequestUtils.execute(mOkHttpClient, request, listener);
        } else {
            RequestUtils.enqueue(mOkHttpClient, request, listener);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Request(okhttp3.Request) ProgressRequestBody(io.chelizi.amokhttp.upload.ProgressRequestBody) RequestBody(okhttp3.RequestBody)

Example 8 with CacheControl

use of okhttp3.CacheControl in project MVPFrames by RockyQu.

the class NetworkInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    // 在请求服务器之前可以拿到request,做一些操作比如给request添加header,如果不需要操作则返回参数中的request
    if (handler != null) {
        request = handler.onHttpRequest(chain, request);
    }
    NetworkStatusReceiver.Type type = NetworkStatusReceiver.getType(application);
    if (type == NetworkStatusReceiver.Type.NONE) {
        // 无网络时强制从缓存读取(必须得写,不然断网状态下,退出应用,或者等待一分钟后,会获取不到缓存)
        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
    }
    Response originalResponse = chain.proceed(request);
    if (type == NetworkStatusReceiver.Type.MOBILE || type == NetworkStatusReceiver.Type.WIFI) {
        // 0秒
        int maxAge = 0;
        originalResponse = originalResponse.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "public, max-age=" + maxAge).build();
    } else {
        // 1小时
        int maxTime = 60 * 60;
        originalResponse = originalResponse.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "public, only-if-cached, max-stale=" + maxTime).build();
    }
    // 读取服务器返回的结果
    ResponseBody responseBody = originalResponse.body();
    BufferedSource source = responseBody.source();
    // Buffer the entire body.
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    // 获取content的压缩类型
    String encoding = originalResponse.headers().get("Content-Encoding");
    Buffer clone = buffer.clone();
    String bodyString;
    // 解析response content
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        // content使用gzip压缩
        bodyString = ZipUtils.decompressForGzip(clone.readByteArray());
    } else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {
        // content使用zlib压缩
        bodyString = ZipUtils.decompressToStringForZlib(clone.readByteArray());
    } else {
        // content没有被压缩
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }
        bodyString = clone.readString(charset);
    }
    // 这里可以提前一步拿到服务器返回的结果,外部实现此接口可以做一些操作,比如Token超时,重新获取
    if (handler != null) {
        return handler.onHttpResponse(bodyString, chain, request, originalResponse);
    }
    return originalResponse;
}
Also used : Response(okhttp3.Response) Buffer(okio.Buffer) Request(okhttp3.Request) NetworkStatusReceiver(com.tool.common.http.receiver.NetworkStatusReceiver) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 9 with CacheControl

use of okhttp3.CacheControl in project BestPracticeApp by pop1234o.

the class MainActivity method requestOkHttp.

/**
 * 缓存
 */
private void requestOkHttp() {
    new OkHttpClient.Builder().addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Request request = chain.request();
            // chain.request().newBuilder().addHeader().build()
            okhttp3.Response response = chain.proceed(request);
            return response;
        }
    }).cache(new okhttp3.Cache(getCacheDir(), 5 * 1024 * 1024)).build();
    okhttp3.Request request_forceNocache = new okhttp3.Request.Builder().cacheControl(new CacheControl.Builder().noCache().build()).url("").build();
    okhttp3.Request request_forceCache = new okhttp3.Request.Builder().cacheControl(new CacheControl.Builder().maxAge(0, TimeUnit.SECONDS).build()).url("").build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) StringRequest(com.android.volley.toolbox.StringRequest) Request(com.android.volley.Request) IOException(java.io.IOException) Response(com.android.volley.Response) CacheControl(okhttp3.CacheControl) Interceptor(okhttp3.Interceptor) Cache(com.android.volley.Cache) DiskBasedCache(com.android.volley.toolbox.DiskBasedCache)

Example 10 with CacheControl

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()) {
        Response response = chain.proceed(request);
        // read from cache for 60 s
        int maxAge = 60;
        String cacheControl = request.cacheControl().toString();
        Log.d(TAG, "60s load cahe" + cacheControl);
        return response.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "public, max-age=" + maxAge).build();
    } else {
        // ((Activity) context).runOnUiThread(new Runnable() {
        // @Override
        // public void run() {
        // Toast.makeText(context, "当前无网络! 为你智能加载缓存", Toast.LENGTH_SHORT).show();
        // }
        // });
        Log.d(TAG, " no network load cahe");
        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        Response response = chain.proceed(request);
        return response.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).build();
    }
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request)

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