com.facebook.stetho.okhttp3.StethoInterceptor Java Examples

The following examples show how to use com.facebook.stetho.okhttp3.StethoInterceptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpRequestFactory.java    From xifan with Apache License 2.0 7 votes vote down vote up
public HttpRequestFactory() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);

    OkHttpClient okHttpClient =
            new OkHttpClient.Builder().connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .cache(getCache())
                    .addInterceptor(logging)
                    .addNetworkInterceptor(mTokenInterceptor)
                    //应用拦截器,用于离线缓存
                    .addInterceptor(mCacheInterceptor)
                    //网络拦截器,用于在线缓存
                    .addNetworkInterceptor(mCacheInterceptor)
                    .addNetworkInterceptor(new StethoInterceptor())
                    .build();

    Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.FanFou.FANFOU_API_URL)
            .addConverterFactory(ResponseConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(okHttpClient)
            .build();

    mServiceFactory = retrofit.create(ApiFactory.class);
}
 
Example #2
Source File: GlideModule.java    From glide-support with The Unlicense 6 votes vote down vote up
@Override public void registerComponents(Context context, Glide glide) {
		Stetho.initializeWithDefaults(context);
		final Cache cache = new Cache(new File(context.getCacheDir(), "okhttp"), IMAGE_CACHE_SIZE);

		HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
//		logger.setLevel(Level.BASIC);

		OkHttpClient client = new OkHttpClient()
				.newBuilder()
				.cache(cache)
				.addNetworkInterceptor(new StethoInterceptor())
				.addInterceptor(logger)
				.build();

		glide.register(CachedGlideUrl.class, InputStream.class,
				superFactory(new OkHttpUrlLoader.Factory(client), CachedGlideUrl.class));
		glide.register(ForceLoadGlideUrl.class, InputStream.class,
				superFactory(new OkHttpUrlLoader.Factory(client), ForceLoadGlideUrl.class));
	}
 
Example #3
Source File: OAuthAsyncHttpClient.java    From android-oauth-handler with MIT License 6 votes vote down vote up
public static OAuthAsyncHttpClient create(final OAuth2AccessToken token) {
    final String bearer = String.format("%s %s", BEARER, token.getAccessToken());

    HttpLoggingInterceptor logging = createLogger();

    OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .addNetworkInterceptor(new StethoInterceptor())
            .addInterceptor(new Interceptor() {
                                @NotNull
                                @Override
                                public Response intercept(@NotNull Chain chain) throws IOException {
                                    Request originalRequest = chain.request();
                                    Request authedRequest = originalRequest.newBuilder().header("Authorization", bearer).build();
                                    return chain.proceed(authedRequest);
                                }
                            }).build();

    OAuthAsyncHttpClient asyncHttpClient = new OAuthAsyncHttpClient(httpClient);
    return asyncHttpClient;
}
 
Example #4
Source File: AppModule.java    From jianshi with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
OkHttpClient provideOkHttpClient(GlobalRequestInterceptor globalRequestInterceptor) {
  OkHttpClient.Builder builder = new OkHttpClient.Builder()
      .connectionPool(new ConnectionPool(5, 59, TimeUnit.SECONDS))
      .connectTimeout(20, TimeUnit.SECONDS)
      .readTimeout(20, TimeUnit.SECONDS)
      .addInterceptor(globalRequestInterceptor)
      .retryOnConnectionFailure(false);
  if (BuildConfig.DEBUG) {
    builder.addNetworkInterceptor(new StethoInterceptor());
  }

  HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
  httpLoggingInterceptor.setLevel(
      BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
  builder.addInterceptor(httpLoggingInterceptor);

  return builder.build();
}
 
Example #5
Source File: ApiServiceFactory.java    From zhizhihu with Apache License 2.0 6 votes vote down vote up
/**
 * 每个获取 APIService 的方法都在先检测 sHttpClient 是否为空
 */
private static void initHttpClient() {
    OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
    File file = new File(App.getContext().getCacheDir(), "ResponseCache");
    builder.cache(new Cache(file, AppConfig.RESPONSE_CACHE_SIZE))
            .readTimeout(AppConfig.READ_TIME_OUT, TimeUnit.SECONDS)
            .connectTimeout(AppConfig.CONNECTION_TIME_OUT, TimeUnit.SECONDS);
    if (AppConfig.isDebug) {
        // TODO: 2016/3/19 Release 版本需要注释此拦截器
        builder.addNetworkInterceptor(new StethoInterceptor());
        builder.addInterceptor(LoggingInterceptor);
    }
    builder.addNetworkInterceptor(HttpInterceptor);
    builder.addInterceptor(HttpInterceptor);
    sHttpClient = builder.build();
}
 
Example #6
Source File: RetrofitHelper.java    From gank.io-unofficial-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化OKHttpClient
 */
private static void initOkHttpClient() {

  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
  interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  if (mOkHttpClient == null) {
    synchronized (RetrofitHelper.class) {
      if (mOkHttpClient == null) {
        //设置Http缓存
        Cache cache = new Cache(new File(GankApp.getContext().getCacheDir(), "HttpCache"),
            1024 * 1024 * 100);

        mOkHttpClient = new OkHttpClient.Builder()
            .cache(cache)
            .addInterceptor(interceptor)
            .addNetworkInterceptor(new StethoInterceptor())
            .retryOnConnectionFailure(true)
            .connectTimeout(15, TimeUnit.SECONDS)
            .build();
      }
    }
  }
}
 
Example #7
Source File: ServerModule.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static D2Configuration getD2Configuration(Context context) {
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.add(new StethoInterceptor());
    interceptors.add(new AnalyticsInterceptor(
            new AnalyticsHelper(FirebaseAnalytics.getInstance(context),
                    new PreferenceProviderImpl(context))));
    return D2Configuration.builder()
            .appName(BuildConfig.APPLICATION_ID)
            .appVersion(BuildConfig.VERSION_NAME)
            .connectTimeoutInSeconds(3 * 60)
            .readTimeoutInSeconds(3 * 60)
            .networkInterceptors(interceptors)
            .writeTimeoutInSeconds(3 * 60)
            .context(context)
            .build();
}
 
Example #8
Source File: RetrofitHelper.java    From MoeQuest with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化OKHttpClient
 */
private static void initOkHttpClient() {

  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
  interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  if (mOkHttpClient == null) {
    synchronized (RetrofitHelper.class) {
      if (mOkHttpClient == null) {
        //设置Http缓存
        Cache cache = new Cache(new File(MoeQuestApp.getContext().getCacheDir(), "HttpCache"),
            1024 * 1024 * 100);

        mOkHttpClient = new OkHttpClient.Builder()
            .cache(cache)
            .addInterceptor(interceptor)
            .addNetworkInterceptor(new StethoInterceptor())
            .retryOnConnectionFailure(true)
            .connectTimeout(20, TimeUnit.SECONDS)
            .build();
      }
    }
  }
}
 
Example #9
Source File: SampleApplication.java    From px-android with MIT License 6 votes vote down vote up
private void initializeLeakCanary() {
    if (LeakCanary.isInAnalyzerProcess(this)) {
        return;
    }
    LeakCanary.install(this);
    Stetho.initializeWithDefaults(this);

    // Create client base, add interceptors
    OkHttpClient.Builder baseClient = HttpClientUtil.createBaseClient(this, 10, 10, 10)
        .addNetworkInterceptor(new StethoInterceptor());

    // customClient: client with TLS protocol setted
    final OkHttpClient customClient = HttpClientUtil.enableTLS12(baseClient)
        .build();

    HttpClientUtil.setCustomClient(customClient);

    Dependencies.getInstance().initialize(getApplicationContext());

    final ESCManagerBehaviour escManagerBehaviour = new FakeEscManagerBehaviourImpl();
    new PXBehaviourConfigurer()
        .with(new MockSecurityBehaviour(escManagerBehaviour))
        .with(escManagerBehaviour)
        .with(FakeLocaleBehaviourImpl.INSTANCE)
        .configure();
}
 
Example #10
Source File: RemoteManager.java    From JianshuApp with GNU General Public License v3.0 5 votes vote down vote up
private RemoteManager() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder()
                .connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(HTTP_WRITE_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(new UnifiedParameterInterceptor());
        if (!VersionChannel.isStable()) {
            httpClientBuilder.addInterceptor(new LoggingInterceptor());
            httpClientBuilder.hostnameVerifier((hostname, session) -> true);
        }
        if (!VersionChannel.isUnitTest()) {
            httpClientBuilder.cache(new Cache(getHttpCacheDir(), RESPONSE_CACHE_SIZE));

            if (VersionChannel.isDebug()) {
                httpClientBuilder.addNetworkInterceptor(new StethoInterceptor());
            }
        }
        httpClient = httpClientBuilder.build();

        gson = new GsonBuilder()
                .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
                .create();

        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .baseUrl(API_HOST_URL)
                .client(httpClient)
                .addConverterFactory(CustomGsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        retrofit = retrofitBuilder.build();

        // TODO 支持缓存功能
//        CacheUtils.isDebug(false);
//        CacheUtils.init(DataLayer.getContext(), getKakaCacheDir());
    }
 
Example #11
Source File: FakeServerModule.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static D2Configuration getD2Configuration() {
    return D2Configuration.builder()
            .appName("app_name")
            .appVersion("1.0.0")
            .networkInterceptors(Lists.newArrayList(new StethoInterceptor()))
            .context(ApplicationProvider.getApplicationContext())
            .build();
}
 
Example #12
Source File: OAuthAsyncHttpClient.java    From android-oauth-handler with MIT License 5 votes vote down vote up
public static OAuthAsyncHttpClient create(String consumerKey, String consumerSecret, OAuth1AccessToken token) {
    OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(consumerKey, consumerSecret);
    HttpLoggingInterceptor logging = createLogger();

    consumer.setTokenWithSecret(token.getToken(), token.getTokenSecret());
    OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .addNetworkInterceptor(new StethoInterceptor())
            .addInterceptor(new SigningInterceptor(consumer)).build();

    OAuthAsyncHttpClient asyncHttpClient = new OAuthAsyncHttpClient(httpClient);
    return asyncHttpClient;
}
 
Example #13
Source File: GithubApiService.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
private GithubApiService() {
    OkHttpClient.Builder httpclientBuilder = new OkHttpClient.Builder();
    httpclientBuilder.connectTimeout(5, TimeUnit.SECONDS);
    httpclientBuilder.addNetworkInterceptor(new StethoInterceptor());
    retrofit = new Retrofit.Builder().client(httpclientBuilder.build()).addConverterFactory(GsonConverterFactory.create()).
            addCallAdapterFactory(RxJavaCallAdapterFactory.create()).baseUrl(BASE_URL).build();
    githubApiServiceInterface = retrofit.create(GithubApiServiceInterface.class);

}
 
Example #14
Source File: WallabagConnection.java    From android-app with GNU General Public License v3.0 5 votes vote down vote up
private static OkHttpClient.Builder getClientBuilder(boolean addCookieManager) {
    OkHttpClient.Builder b = new OkHttpClient.Builder()
            .readTimeout(45, TimeUnit.SECONDS);

    if(addCookieManager) {
        b.cookieJar(new JavaNetCookieJar(new CookieManager(null, CookiePolicy.ACCEPT_ALL)));
    }

    if(BuildConfig.DEBUG) {
        b.addInterceptor(new LoggingInterceptor());
        b.addNetworkInterceptor(new StethoInterceptor());
    }

    return b;
}
 
Example #15
Source File: ImagePipelineConfigFactory.java    From fresco with MIT License 5 votes vote down vote up
/** Creates config using OkHttp as network backed. */
public static ImagePipelineConfig getOkHttpImagePipelineConfig(Context context) {
  if (sOkHttpImagePipelineConfig == null) {
    OkHttpClient okHttpClient =
        new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build();
    ImagePipelineConfig.Builder configBuilder =
        OkHttpImagePipelineConfigFactory.newBuilder(context, okHttpClient);
    configureCaches(configBuilder, context);
    configureLoggingListeners(configBuilder);
    sOkHttpImagePipelineConfig = configBuilder.build();
  }
  return sOkHttpImagePipelineConfig;
}
 
Example #16
Source File: D2Factory.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static D2Configuration d2Configuration(Context context) {
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    return D2Configuration.builder()
            .appVersion("1.0.0")
            .readTimeoutInSeconds(30)
            .connectTimeoutInSeconds(30)
            .writeTimeoutInSeconds(30)
            .networkInterceptors(Collections.singletonList(new StethoInterceptor()))
            .interceptors(Collections.singletonList(loggingInterceptor))
            .context(context)
            .build();
}
 
Example #17
Source File: UnsafeHttpClientFactory.java    From quill with MIT License 5 votes vote down vote up
@Override
public OkHttpClient create(@Nullable File cacheDir) {
    return super.create(cacheDir).newBuilder()
            // allow inspecting network requests with Chrome DevTools
            .addNetworkInterceptor(new StethoInterceptor())
            // log requests and responses
            .addInterceptor(new HttpLoggingInterceptor()
                    .setLevel(HttpLoggingInterceptor.Level.BODY))
            // trust all SSL certs, for TESTING ONLY!
            .hostnameVerifier((hostname, session) -> true)
            .sslSocketFactory(getUnsafeSslSocketFactory(), mGullibleTrustManager)
            .build();
}
 
Example #18
Source File: AppModule.java    From Anago with Apache License 2.0 5 votes vote down vote up
@Singleton
@Provides
public OkHttpClient provideOkHttp() {
    return new OkHttpClient.Builder()
            .addNetworkInterceptor(new StethoInterceptor())
            .build();
}
 
Example #19
Source File: RetrofitHelper.java    From HeroVideo-master with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化OKHttpClient,设置缓存,设置超时时间,设置打印日志,设置UA拦截器
 */
private static void initOkHttpClient()
{

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    if (mOkHttpClient == null)
    {
        synchronized (RetrofitHelper.class)
        {
            if (mOkHttpClient == null)
            {
                //设置Http缓存
                Cache cache = new Cache(new File(HeroVideoApp.getInstance()
                        .getCacheDir(), "HttpCache"), 1024 * 1024 * 10);

                mOkHttpClient = new OkHttpClient.Builder()
                        .cache(cache)
                        .addInterceptor(interceptor)
                        .addNetworkInterceptor(new CacheInterceptor())
                        .addNetworkInterceptor(new StethoInterceptor())
                        .retryOnConnectionFailure(true)
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(20, TimeUnit.SECONDS)
                        .readTimeout(20, TimeUnit.SECONDS)
                      //  .addInterceptor(new UserAgentInterceptor())
                        .build();
            }
        }
    }
}
 
Example #20
Source File: RetrofitHelper.java    From HeroVideo-master with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化OKHttpClient,设置缓存,设置超时时间,设置打印日志,设置UA拦截器
 */
private static void initOkHttpClient()
{

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    if (mOkHttpClient == null)
    {
        synchronized (RetrofitHelper.class)
        {
            if (mOkHttpClient == null)
            {
                //设置Http缓存
                Cache cache = new Cache(new File(HeroVideoApp.getInstance()
                        .getCacheDir(), "HttpCache"), 1024 * 1024 * 10);

                mOkHttpClient = new OkHttpClient.Builder()
                        .cache(cache)
                        .addInterceptor(interceptor)
                        .addNetworkInterceptor(new CacheInterceptor())
                        .addNetworkInterceptor(new StethoInterceptor())
                        .retryOnConnectionFailure(true)
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(20, TimeUnit.SECONDS)
                        .readTimeout(20, TimeUnit.SECONDS)
                      //  .addInterceptor(new UserAgentInterceptor())
                        .build();
            }
        }
    }
}
 
Example #21
Source File: AndroidHttpClientFactory.java    From pretixdroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
public OkHttpClient buildClient() {
    if (BuildConfig.DEBUG) {
        return new OkHttpClient.Builder()
                .addNetworkInterceptor(new StethoInterceptor())
                .build();
    } else {
        return new OkHttpClient.Builder()
                .build();
    }
}
 
Example #22
Source File: DemoApplication.java    From ExoPlayer-Offline with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
  super.onCreate();
  INSTANCE = this;
  userAgent = Util.getUserAgent(this, "ExoPlayerDemo");
  okHttpClient = new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build();
  Stetho.initializeWithDefaults(this);
}
 
Example #23
Source File: MainApplication.java    From Android-OkGraphQl with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    Stetho.initializeWithDefaults(getApplicationContext());
    okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new StethoInterceptor())
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build();
}
 
Example #24
Source File: RetrofitClientApp.java    From RetrofitGO with Apache License 2.0 5 votes vote down vote up
/**
     * 初始化默认的RetrofitClient
     * @param application
     * @param debug
     */
    public static void initDefaultRetrofitClient(Application application, boolean debug) {
        RetrofitConfig.Builder builder = new RetrofitConfig.Builder()
                .addConverterFactory(CommonGsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
//                .addInterceptor(new CommonRequestHeadersInterceptor())
//                .addInterceptor(new CommonRequestParamsInterceptor());


        if (debug) {
            // 添加日志拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("RetrofitClient", "OkHttp====Message:" + message);
                }
            });
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //日志拦截器需要放到其它拦截器后面,不然有些信息打印不出,比如请求头信息
            //OkHttp进行添加拦截器loggingInterceptor
            builder.addInterceptor(loggingInterceptor);

            // 添加Stetho调试拦截器,并初始化
            builder.addNetworkInterceptor(new StethoInterceptor());
            Stetho.initializeWithDefaults(application);
        }

        RetrofitClient.init(application, builder.build());
    }
 
Example #25
Source File: OkHttpModule.java    From android with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@Named("network")
List<Interceptor> provideOkHttpNetworkInterceptors() {
    List<Interceptor> list = new ArrayList<>();
    list.add(new StethoInterceptor());
    return list;
}
 
Example #26
Source File: AppModule.java    From Open-Mam with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public OkHttpClient provideMainOkHttp() {
    return new OkHttpClient.Builder()
            .addInterceptor(new StethoInterceptor())
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build();
}
 
Example #27
Source File: ProductHuntRestApi.java    From Capstone-Project with MIT License 5 votes vote down vote up
private static OkHttpClient getOkHttpClient(boolean withInterceptor) {
    OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
    okHttpClientBuilder.addNetworkInterceptor(new StethoInterceptor());
    okHttpClientBuilder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS);
    okHttpClientBuilder.readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS);
    okHttpClientBuilder.writeTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS);

    if (withInterceptor) {
        okHttpClientBuilder.addInterceptor(sInterceptor);
    }

    return okHttpClientBuilder.build();
}
 
Example #28
Source File: StethoInitializer.java    From android with Apache License 2.0 4 votes vote down vote up
public static void addInterceptor(List<Interceptor> list) {
  list.add(new StethoInterceptor());
}
 
Example #29
Source File: HttpModule.java    From Awesome-WanAndroid with Apache License 2.0 4 votes vote down vote up
@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
    // 网络请求质量监控
    builder.eventListenerFactory(OkHttpEventListener.FACTORY);
    // httpDns 优化
    builder.dns(OkHttpDns.getIns(WanAndroidApp.getAppComponent().getContext()));

    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);

    if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        builder.addInterceptor(loggingInterceptor);
        builder.addNetworkInterceptor(new StethoInterceptor());
    }

    //设置超时
    builder.connectTimeout(10, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    //错误重连
    builder.retryOnConnectionFailure(true);
    //cookie认证
    builder.cookieJar(new PersistentCookieJar(new SetCookieCache(),
            new SharedPrefsCookiePersistor(WanAndroidApp.getInstance())));
    return RetrofitUrlManager.getInstance().with(builder).build();
}
 
Example #30
Source File: OkHttpModule.java    From droidconat-2016 with Apache License 2.0 4 votes vote down vote up
@Provides @Singleton OkHttpClient provideOkHttpClient(OkHttpClient.Builder builder) {
    return builder.addNetworkInterceptor(new StethoInterceptor()).build();
}