All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cmonbaby.http.utils.OkHttp3Utils Maven / Gradle / Ivy

There is a newer version: 3.0.3
Show newest version
package com.cmonbaby.http.utils;

import com.cmonbaby.http.HttpManager;
import com.cmonbaby.http.https.HttpsUtils;
import com.cmonbaby.http.logger.HttpLoggingInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;

/**
 * 

Author: Simon *

QO: 8950764 *

Email: [email protected] *

WebSize: https://www.cmonbaby.com *

Version: 1.0.0 *

Date: 2020/12/28 *

Description: 封装一个OkHttp3的获取类 */ class OkHttp3Utils { private static OkHttpClient.Builder mOkHttpClient; /** * 获取OkHttpClient对象 * * @return OkHttpClient */ static OkHttpClient.Builder getOkHttpClient() { if (mOkHttpClient == null) { // 同样okhttp3后也使用build设计模式 OkHttpClient.Builder builder = new OkHttpClient.Builder(); // 设置一个自动管理cookies的管理器 // builder.cookieJar(new CookiesManager()) // 添加拦截器,log,统一的header等 if (HttpManager.interceptor() != null) builder.addInterceptor(HttpManager.interceptor()); // 添加网络连接器 // builder.addNetworkInterceptor(new CookiesInterceptor(MyApplication.getInstance().getApplicationContext())) if (HttpManager.isShowLogger()) builder.addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); // 添加hostName验证器 if (HttpManager.hostName() != null) builder.hostnameVerifier(HttpManager.hostName()); // 添加Https证书验证 if (HttpManager.sslSocketFactory() != null) { HttpsUtils.SSLParams sslParams = HttpManager.sslSocketFactory(); builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager); builder.hostnameVerifier((hostname, session) -> true); } // 设置请求读写的超时时间 builder.connectTimeout(30, TimeUnit.SECONDS); builder.writeTimeout(30, TimeUnit.SECONDS); builder.readTimeout(30, TimeUnit.SECONDS); // 这里可以根据自己的机型设置同时连接的个数和时间,默认10个,和每个保持时间为30s builder.connectionPool(new ConnectionPool(10, 30, TimeUnit.SECONDS)); // 错误重连 builder.retryOnConnectionFailure(true); mOkHttpClient = builder; } return mOkHttpClient; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy