HttpClients 工具类

public class HttpClientUtils {
private static final Logger LOGGER = Logger.getLogger(HttpClientUtils.class);

private static int SOCKET_TIMEOUT = 20000;
private static int CONNECT_TIMEOUT = 20000;
private static int CONNECT_REQUEST_TIMEOUT = 20000;
private static int MAX_TOTAL = 200;
private static int REQUEST_RETRY = 3;

// private static String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 8.0;
// Windows XP)";

private static RequestConfig requestConfig = null;
private static PoolingHttpClientConnectionManager conMgr = null;
private static DefaultHttpRequestRetryHandler retryHandler = null;
private static LaxRedirectStrategy redirectStrategy = null;
private static SSLConnectionSocketFactory sslsf = null;

private static HttpClientUtils instance = null;

private HttpClientUtils() {
}

public static HttpClientUtils getInstance() {
if (instance == null) {
synchronized (HttpClientUtils.class) {
if (instance == null) {
/*
* setSocketTimeout setConnectTimeout
* setConnectionRequestTimeout
*/
requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT).build();

conMgr = new PoolingHttpClientConnectionManager();
// 设置整个连接池最大连接数 根据自己的场景决定
conMgr.setMaxTotal(MAX_TOTAL);
// 是路由的默认最大连接(该值默认为2),限制数量实际使用DefaultMaxPerRoute并非MaxTotal。
// 设置过小无法支持大并发(ConnectionPoolTimeoutException: Timeout
// waiting for connection from pool),路由是对maxTotal的细分。
// (目前只有一个路由,因此让他等于最大值)
conMgr.setDefaultMaxPerRoute(conMgr.getMaxTotal());

// 另外设置http client的重试次数,默认是3次;当前是禁用掉(如果项目量不到,这个默认即可)
retryHandler = new DefaultHttpRequestRetryHandler(REQUEST_RETRY, true);

// 设置重定向策略
redirectStrategy = new LaxRedirectStrategy();

// 自签名策略
try {
final SSLContextBuilder sSLContextBuilder = new SSLContextBuilder();
sSLContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
sslsf = new SSLConnectionSocketFactory(sSLContextBuilder.build());
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e.getLocalizedMessage(), e);
} catch (KeyStoreException e) {
LOGGER.error(e.getLocalizedMessage(), e);
} catch (KeyManagementException e) {
LOGGER.error(e.getLocalizedMessage(), e);
}

// 创建HttpClientBuilder
// HttpClientBuilder httpClientBuilder =
// HttpClientBuilder.create();
// httpClient =
// httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig).build();
// httpClient =
// HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(conMgr).setRetryHandler(retryHandler).setRedirectStrategy(redirectStrategy).setSSLSocketFactory(sslsf).build();

instance = new HttpClientUtils();
}
}
}
return instance;
}

猜你喜欢

转载自blog.csdn.net/qq_34567887/article/details/80462803