Search in sources :

Example 66 with Interceptor

use of okhttp3.Interceptor in project RxSample by Aload.

the class RequestManger method getRetrofit.

/**
     * 获取retrofit对象
     *
     * @param mListener
     * @return
     */
public Retrofit getRetrofit(IBaseRXListener mListener) {
    String url = mListener.getUrl();
    if (null == mRetrofit || !url.equals(mRetrofit.baseUrl().toString())) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder().readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).addInterceptor(//拦截器处理通用Header
        interceptor).addInterceptor(//日志处理
        loggingInterceptor).connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        //可以区别http,https
        if (!StringUtil.isNullOrEmpty(url) && url.toLowerCase().contains("https:")) {
            try {
                builder.sslSocketFactory(getSSLSocketFactory(new int[] { mListener.getRawSSl() }));
                builder.hostnameVerifier(new HostVerifyUtils(new String[] { url }));
            } catch (Exception e) {
                mListener.getException(e);
            }
        }
        OkHttpClient client = builder.build();
        mRetrofit = new Retrofit.Builder().client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).baseUrl(url).build();
    }
    return mRetrofit;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) HostVerifyUtils(com.autism.rxsample.utils.rxutils.HostVerifyUtils) IOException(java.io.IOException)

Example 67 with Interceptor

use of okhttp3.Interceptor in project Atom_Android by Rogrand-Dev.

the class HttpModule method provideClient.

@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
    if (DemoApp.getAppContext().isDebug()) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

            @Override
            public void log(String message) {
                LogUtils.i(TAG, message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        // 设置 Log 拦截器
        builder.addInterceptor(loggingInterceptor);
    }
    File cacheFile = new File(DataUtils.getCacheFile(DemoApp.getAppContext()), "RograndCache");
    // 100 MB
    int cacheSize = 100 * 1024 * 1024;
    Cache cache = new Cache(cacheFile, cacheSize);
    Interceptor cacheInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            CacheControl.Builder cacheBuilder = new CacheControl.Builder();
            cacheBuilder.maxAge(0, TimeUnit.SECONDS);
            cacheBuilder.maxStale(365, TimeUnit.DAYS);
            CacheControl cacheControl = cacheBuilder.build();
            Request request = chain.request();
            if (!NetUtils.isNetworkAvailable(DemoApp.getAppContext())) {
                request = request.newBuilder().cacheControl(cacheControl).build();
            }
            Response response = chain.proceed(request);
            if (NetUtils.isNetworkAvailable(DemoApp.getAppContext())) {
                // 有网络时, 不缓存, 最大保存时长为0
                int maxAge = 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;
        }
    };
    // 设置 header(设置 Token、API 版本号)
    Interceptor headerInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request = request.newBuilder().addHeader("Authorization", "Bearer " + SPUtils.get(DemoApp.getAppContext(), Constants.ACCESS_TOKEN, "")).addHeader("api_version", UrlConstants.API_VERSION).build();
            return chain.proceed(request);
        }
    };
    // 设置统一的请求头部参数
    builder.addInterceptor(headerInterceptor);
    // 设置缓存
    builder.addNetworkInterceptor(cacheInterceptor);
    builder.addInterceptor(cacheInterceptor);
    builder.cache(cache);
    // 设置连接超时
    builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
    // 设置读取数据超时
    builder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
    // 设置写入数据超时
    builder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
    // 设置 Stetho
    builder.addNetworkInterceptor(new StethoInterceptor());
    // 设置 Cookie
    builder.cookieJar(new CookieManger(DemoApp.getAppContext()));
    // 错误重连
    builder.retryOnConnectionFailure(true);
    return builder.build();
}
Also used : CookieManger(com.rogrand.demo.http.cookie.CookieManger) Request(okhttp3.Request) Response(okhttp3.Response) CacheControl(okhttp3.CacheControl) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) File(java.io.File) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 68 with Interceptor

use of okhttp3.Interceptor in project smartmodule by carozhu.

the class HttpDownloadHelper method creatService.

public <S> S creatService(Class<S> serviceClass, final ProgressListener progressListener) {
    //给httpClient添加拦截器
    httpClient.addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response originalResponse = chain.proceed(chain.request());
            ProgressResponseBody responseBody = new ProgressResponseBody(originalResponse.body(), progressListener);
            return originalResponse.newBuilder().body(responseBody).build();
        }
    });
    Retrofit retrofit = builder.build();
    return retrofit.create(serviceClass);
}
Also used : Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 69 with Interceptor

use of okhttp3.Interceptor in project chefly_android by chef-ly.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();
    long t1 = System.nanoTime();
    Log.d("Interceptor", (String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())));
    Response response = chain.proceed(request);
    long t2 = System.nanoTime();
    Log.d("Interceptor", (String.format(Locale.US, "Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())));
    return response;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request)

Example 70 with Interceptor

use of okhttp3.Interceptor in project Varis-Android by dkhmelenko.

the class NetworkModule method okHttpClient.

@Provides
@Singleton
public OkHttpClient okHttpClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return new OkHttpClient.Builder().addInterceptor(interceptor).followRedirects(false).followSslRedirects(false).build();
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Aggregations

IOException (java.io.IOException)35 Interceptor (okhttp3.Interceptor)33 MockResponse (okhttp3.mockwebserver.MockResponse)29 Request (okhttp3.Request)26 Test (org.junit.Test)25 Response (okhttp3.Response)24 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)24 OkHttpClient (okhttp3.OkHttpClient)20 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)10 File (java.io.File)8 Provides (dagger.Provides)6 Singleton (javax.inject.Singleton)6 Cache (okhttp3.Cache)4 Retrofit (retrofit2.Retrofit)4 InterruptedIOException (java.io.InterruptedIOException)3 Call (okhttp3.Call)3 HttpUrl (okhttp3.HttpUrl)3 NonNull (android.support.annotation.NonNull)2 ANResponse (com.androidnetworking.common.ANResponse)2 ResponseProgressBody (com.androidnetworking.internal.ResponseProgressBody)2