cn.cliveyuan.tools.httpclient.HttpClientSingleton Maven / Gradle / Ivy
The newest version!
package cn.cliveyuan.tools.httpclient;
import cn.cliveyuan.tools.httpclient.ssl.SSL;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.internal.Util;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author Clive Yuan
* @date 2021/06/08
*/
public class HttpClientSingleton {
/**
* 获取okHttpClient单例
*
* @return
*/
public static OkHttpClient getOkHttpClient() {
return OkHttpClientSingletonHolder.OK_HTTP_CLIENT;
}
private static class OkHttpClientSingletonHolder {
private static final OkHttpClient OK_HTTP_CLIENT;
static {
ThreadPoolExecutor executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false));
Dispatcher dispatcher = new Dispatcher(executorService);
dispatcher.setMaxRequestsPerHost(250);
dispatcher.setMaxRequests(2000);
OkHttpClient.Builder clientBuilder = new OkHttpClient
.Builder()
.dispatcher(dispatcher)
.followRedirects(false)
.followSslRedirects(false)
.connectionPool(new ConnectionPool(128, 900, TimeUnit.SECONDS))
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.sslSocketFactory(SSL.sslSocketFactory, SSL.x509TrustManager)
.hostnameVerifier(SSL.hostnameVerifier);
OK_HTTP_CLIENT = clientBuilder.build();
}
}
}