Search in sources :

Example 56 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project storio by pushtorefresh.

the class ChainImplTest method buildChain_shouldThrowIfRealInterceptorNull.

@Test
public void buildChain_shouldThrowIfRealInterceptorNull() {
    try {
        final List<Interceptor> interceptors = Collections.singletonList(mock(Interceptor.class));
        // noinspection ConstantConditions
        final Chain chain = ChainImpl.buildChain(interceptors, null);
        chain.proceed(mock(PreparedOperation.class));
        failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
    } catch (IllegalArgumentException e) {
        assertThat(e).hasMessage("Interceptor should not be null");
    }
}
Also used : Chain(com.pushtorefresh.storio3.Interceptor.Chain) PreparedOperation(com.pushtorefresh.storio3.operations.PreparedOperation) Interceptor(com.pushtorefresh.storio3.Interceptor) Test(org.junit.Test)

Example 57 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project smartmodule by carozhu.

the class OkHttpUtils method getInstance.

public static OkHttpClient.Builder getInstance(final Context context) {
    if (singleton == null) {
        synchronized (OkHttpUtils.class) {
            if (singleton == null) {
                singleton = new OkHttpClient().newBuilder();
                singleton.connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS);
                singleton.readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS);
                // okhttp设置错误重新连接
                singleton.retryOnConnectionFailure(true);
                // singleton.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR);
                // singleton.addInterceptor(REWRITE_RESPONSE_INTERCEPTOR_OFFLINE);
                File cacheDir = new File(context.getCacheDir(), RESPONSE_CACHE);
                singleton.cache(new Cache(cacheDir, RESPONSE_CACHE_SIZE));
                if (ConfigureManager.getConfigureManager().isOkhttpLogger()) {
                    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    singleton.addInterceptor(interceptor);
                }
                if (ConfigureManager.getConfigureManager().isOkhttpCache()) {
                    // 设置缓存路径
                    File httpCacheDirectory = new File(context.getCacheDir(), "httpCacheResponses");
                    // 设置缓存 100M
                    Cache cache = new Cache(httpCacheDirectory, RESPONSE_CACHE_SIZE);
                    Interceptor myinterceptor = new Interceptor() {

                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request();
                            Log.i(TAG, "request=" + request);
                            if (!NetworkUtil.isNetworkAvailable(context)) {
                                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
                                Log.i(TAG, "no network");
                            }
                            Response response = chain.proceed(request);
                            if (NetworkUtil.isNetworkAvailable(context)) {
                                // 有网络时 设置缓存超时时间0个小时
                                int maxAge = 0 * 60;
                                Log.i(TAG, "has network maxAge=" + maxAge);
                                response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader(// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
                                "Pragma").build();
                            } else {
                                Log.i(TAG, "network error");
                                // 无网络时,设置超时为4周
                                int maxStale = 60 * 60 * 24 * 28;
                                Log.i(TAG, "has maxStale=" + maxStale);
                                response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
                                Log.i(TAG, "response build maxStale=" + maxStale);
                            }
                            return response;
                        }
                    };
                    singleton.addInterceptor(myinterceptor).cache(cache);
                }
            }
        }
    }
    return singleton;
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache)

Example 58 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project MVPArms by JessYanCoding.

the class ClientModule method provideClient.

/**
 * 提供 {@link OkHttpClient}
 *
 * @param application     {@link Application}
 * @param configuration   {@link OkhttpConfiguration}
 * @param builder         {@link OkHttpClient.Builder}
 * @param intercept       {@link Interceptor}
 * @param interceptors    {@link List<Interceptor>}
 * @param handler         {@link GlobalHttpHandler}
 * @param executorService {@link ExecutorService}
 * @return {@link OkHttpClient}
 */
@Singleton
@Provides
static OkHttpClient provideClient(Application application, @Nullable OkhttpConfiguration configuration, OkHttpClient.Builder builder, Interceptor intercept, @Nullable List<Interceptor> interceptors, @Nullable GlobalHttpHandler handler, ExecutorService executorService) {
    builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS).readTimeout(TIME_OUT, TimeUnit.SECONDS).addNetworkInterceptor(intercept);
    if (handler != null) {
        builder.addInterceptor(chain -> chain.proceed(handler.onHttpRequestBefore(chain, chain.request())));
    }
    // 如果外部提供了 Interceptor 的集合则遍历添加
    if (interceptors != null) {
        for (Interceptor interceptor : interceptors) {
            builder.addInterceptor(interceptor);
        }
    }
    // 为 OkHttp 设置默认的线程池
    builder.dispatcher(new Dispatcher(executorService));
    if (configuration != null) {
        configuration.configOkhttp(application, builder);
    }
    return builder.build();
}
Also used : Dispatcher(okhttp3.Dispatcher) RequestInterceptor(com.jess.arms.http.log.RequestInterceptor) Interceptor(okhttp3.Interceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 59 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project ride-read-android by Ride-Read.

the class RetrofitUtils method addQueryParameterInterceptor.

/**
 * 设置公共参数
 */
private static Interceptor addQueryParameterInterceptor() {
    Interceptor addQueryParameterInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request request;
            HttpUrl modifiedUrl = originalRequest.url().newBuilder().addQueryParameter("", Integer.toString(UserUtils.getUid())).addQueryParameter("token", UserUtils.getToken()).build();
            ;
            if (0 != UserUtils.getUid()) {
                modifiedUrl = originalRequest.url().newBuilder().addQueryParameter("uid", Integer.toString(UserUtils.getUid())).addQueryParameter("token", UserUtils.getToken()).build();
            }
            request = originalRequest.newBuilder().url(modifiedUrl).build();
            return chain.proceed(request);
        }
    };
    return addQueryParameterInterceptor;
}
Also used : Request(okhttp3.Request) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpUrl(okhttp3.HttpUrl)

Example 60 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project ride-read-android by Ride-Read.

the class RetrofitUtils method addHeaderInterceptor.

/**
 * 设置头
 */
private static Interceptor addHeaderInterceptor() {
    Interceptor headerInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request.Builder requestBuilder = originalRequest.newBuilder().header("AppType", "TPOS").header("Accept", "application/json").method(originalRequest.method(), originalRequest.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    };
    return headerInterceptor;
}
Also used : Request(okhttp3.Request) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor)

Aggregations

Interceptor (okhttp3.Interceptor)138 Request (okhttp3.Request)61 OkHttpClient (okhttp3.OkHttpClient)54 Response (okhttp3.Response)51 IOException (java.io.IOException)45 Test (org.junit.Test)29 Retrofit (retrofit2.Retrofit)27 File (java.io.File)15 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)13 Cache (okhttp3.Cache)9 HttpUrl (okhttp3.HttpUrl)8 Interceptor (com.pushtorefresh.storio3.Interceptor)7 Dispatcher (okhttp3.Dispatcher)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 X509TrustManager (javax.net.ssl.X509TrustManager)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)5 Provides (dagger.Provides)5 Singleton (javax.inject.Singleton)5 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)5 OAuth (com.arm.mbed.cloud.sdk.internal.devicedirectory.auth.OAuth)4