下面列出了怎么用org.apache.http.config.Registry的API类实例代码及写法,或者点击链接到github查看源代码。
private HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
// Set max total connection
connectionManager.setMaxTotal(maxTotal);
// Set max route connection
connectionManager.setDefaultMaxPerRoute(maxPerRoute);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
}
@Bean
public HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(maxTotal);
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
}
private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException {
try
{
KeyStore keyStore = KeyStoreUtil.createDockerKeyStore(certPath);
SSLContext sslContext =
SSLContexts.custom()
.setProtocol(SSLConnectionSocketFactory.TLS)
.loadKeyMaterial(keyStore, "docker".toCharArray())
.loadTrustMaterial(keyStore, null)
.build();
String tlsVerify = System.getenv("DOCKER_TLS_VERIFY");
SSLConnectionSocketFactory sslsf =
tlsVerify != null && !tlsVerify.equals("0") && !tlsVerify.equals("false") ?
new SSLConnectionSocketFactory(sslContext) :
new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
return RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
}
catch (GeneralSecurityException e) {
// this isn't ideal but the net effect is the same
throw new IOException(e);
}
}
public static void initPool() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
Dict.HTTPS, sslsf).build();
poolConnManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
poolConnManager.setMaxTotal(500);
poolConnManager.setDefaultMaxPerRoute(200);
int socketTimeout = 10000;
int connectTimeout = 10000;
int connectionRequestTimeout = 10000;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
connectTimeout).build();
httpClient = getConnection();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
logger.error("init http client pool failed:", ex);
}
}
private static CloseableHttpClient createClient(SSLConnectionSocketFactory socketFactory) {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", socketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(200); // Increase max total connections to 200, which should be enough
// Have experienced hang in socket read, which may have been because of
// system defaults, therefore set explicit timeouts.
return HttpClientBuilder.create()
.setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG)
.disableAutomaticRetries()
.setUserAgent("node-admin")
.setConnectionManager(cm)
.build();
}
public static PoolingHttpClientConnectionManager getConnctionManager(){
Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
try {
SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
new TrustAllHostNameVerifier());
socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", new PlainConnectionSocketFactory())
.register("https", trustSelfSignedSocketFactory)
.build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
Data.logger.warn("", e);
}
PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ?
new PoolingHttpClientConnectionManager(socketFactoryRegistry):
new PoolingHttpClientConnectionManager();
// twitter specific options
cm.setMaxTotal(2000);
cm.setDefaultMaxPerRoute(200);
return cm;
}
public SimpleHttpClient(SSLContext sslContext, List<String> enabledProtocols, List<String> enabledCiphers,
int listenPort, boolean useCompression) {
HttpClientBuilder builder = HttpClientBuilder.create();
if (!useCompression) {
builder.disableContentCompression();
}
if (sslContext != null) {
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
sslContext,
toArray(enabledProtocols),
toArray(enabledCiphers),
new DefaultHostnameVerifier());
builder.setSSLSocketFactory(sslConnectionFactory);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionFactory)
.build();
builder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
scheme = "https";
} else {
scheme = "http";
}
this.delegate = builder.build();
this.listenPort = listenPort;
}
/**
* 创建httpclient连接池,并初始化httpclient
*/
public void init() {
try {
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
new TrustSelfSignedStrategy())
.build();
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslsf)
.build();
httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// Increase max total connection to 200
httpClientConnectionManager.setMaxTotal(maxTotalPool);
// Increase default max connection per route to 20
httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
} catch (Exception e) {
}
}
private CloseableHttpClient createHttpClient(String hostname, int port) {
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", plainsf).register("https", sslsf).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
// 将最大连接数增加
cm.setMaxTotal(maxTotal);
// 将每个路由基础的连接增加
cm.setDefaultMaxPerRoute(maxPerRoute);
HttpHost httpHost = new HttpHost(hostname, port);
// 将目标主机的最大连接数增加
cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
// 请求重试处理
return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
}
private CloseableHttpClient createHttpClient(String hostname, int port) {
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", plainsf).register("https", sslsf).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
// 将最大连接数增加
cm.setMaxTotal(maxTotal);
// 将每个路由基础的连接增加
cm.setDefaultMaxPerRoute(maxPerRoute);
HttpHost httpHost = new HttpHost(hostname, port);
// 将目标主机的最大连接数增加
cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
// 请求重试处理
return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
}
private Registry<ConnectionSocketFactory> createSocketFactoryRegistry(ConnectionSocketFactory sslSocketFactory) {
/*
* If SSL cert checking for endpoints has been explicitly disabled,
* register a new scheme for HTTPS that won't cause self-signed certs to
* error out.
*/
if (SDKGlobalConfiguration.isCertCheckingDisabled()) {
if (LOG.isWarnEnabled()) {
LOG.warn("SSL Certificate checking for endpoints has been " +
"explicitly disabled.");
}
sslSocketFactory = new TrustingSocketFactory();
}
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
}
/**
* Create a HttpClient
* @return a HttpClient
*/
private HttpClient createHttpClient() {
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1.1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(MercadoPago.SDK.getMaxConnections());
connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);
DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(), false);
HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setConnectionManager(connectionManager)
.setKeepAliveStrategy(new KeepAliveStrategy())
.setRetryHandler(retryHandler)
.disableCookieManagement()
.disableRedirectHandling();
return httpClientBuilder.build();
}
private static HttpClientConnectionManager createConnectionManager(DefaultBotOptions options) {
Registry<ConnectionSocketFactory> registry;
switch (options.getProxyType()) {
case NO_PROXY:
return null;
case HTTP:
registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", new HttpConnectionSocketFactory())
.register("https", new HttpSSLConnectionSocketFactory(SSLContexts.createSystemDefault())).build();
return new PoolingHttpClientConnectionManager(registry);
case SOCKS4:
case SOCKS5:
registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", new SocksConnectionSocketFactory())
.register("https", new SocksSSLConnectionSocketFactory(SSLContexts.createSystemDefault()))
.build();
return new PoolingHttpClientConnectionManager(registry);
}
return null;
}
public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
s_logger.info("Creating new HTTP connection pool and client");
final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration();
final BasicCookieStore cookieStore = new BasicCookieStore();
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connManager.setDefaultMaxPerRoute(MAX_ALLOCATED_CONNECTIONS_PER_ROUTE);
connManager.setMaxTotal(MAX_ALLOCATED_CONNECTIONS);
final RequestConfig requestConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.setMaxRedirects(maxRedirects)
.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
.setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT)
.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT)
.build();
return HttpClientBuilder.create()
.setConnectionManager(connManager)
.setRedirectStrategy(new LaxRedirectStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore)
.setRetryHandler(new StandardHttpRequestRetryHandler())
.build();
}
private static Registry<ConnectionSocketFactory> createRegistry(TLSConfig.Factory tlsConfigFactory) {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
TLSConfig tlsConfig = tlsConfigFactory == null ? null : tlsConfigFactory.create();
if (tlsConfig != null) {
SSLContext sslContext = tlsConfig.getSslContext();
HostnameVerifier hostnameVerifier = tlsConfig.getHostnameVerifier();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
registryBuilder.register("https", socketFactory);
} else {
registryBuilder.register("https", SSLConnectionSocketFactory.getSocketFactory());
}
return registryBuilder.build();
}
protected PoolingHttpClientConnectionManager createConnectionPooling(SSLContext sslContext) {
if (sslContext == null) {
return null;
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
//route is host + port. Since we have only one, set the max and the route the same
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPoolPerRoute);
poolingHttpClientConnectionManager.setMaxTotal(maxPoolTotal);
return poolingHttpClientConnectionManager;
}
protected Registry<ConnectionSocketFactory> getRegistry() {
if (this.protocolregistry == null) {
RegistryBuilder rb = RegistryBuilder.<ConnectionSocketFactory>create();
for (HashMap.Entry<String, ConnectionSocketFactory> entry : protocols.entrySet()) {
rb.register(entry.getKey(), entry.getValue());
}
this.protocolregistry = rb.build();
}
return this.protocolregistry;
}
private static HttpClient createDefaultHttpClient() {
Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(schemeRegistry);
connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
/**
* 使用连接池的 httpclient
*/
@Bean
public HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
// 最大链接数
connectionManager.setMaxTotal(restTemplateProperties.getMaxTotal());
// 同路由并发数20
connectionManager.setDefaultMaxPerRoute(restTemplateProperties.getMaxPerRoute());
RequestConfig requestConfig = RequestConfig.custom()
// 读超时
.setSocketTimeout(restTemplateProperties.getReadTimeout())
// 链接超时
.setConnectTimeout(restTemplateProperties.getConnectTimeout())
// 链接不够用的等待时间
.setConnectionRequestTimeout(restTemplateProperties.getReadTimeout())
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true))
.build();
}
public HttpClientGenerator() {
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", buildSSLConnectionSocketFactory())
.build();
connectionManager = new PoolingHttpClientConnectionManager(reg);
connectionManager.setDefaultMaxPerRoute(100);
}
@Inject
private KairosDB(Gson gson, MetricsServerConfig config) {
this.gson = gson;
this.config = config;
this.executor = new ThreadPoolBuilder()
.withMaxPoolSize(config.getKairosPostThreadsMax())
.withKeepAliveMs(1000)
.withBlockingBacklog()
.withNameFormat("kairos-producer-%d")
.withMetrics("metrics-server.kairos-producer")
.build();
this.uri = URI.create(this.config.getUrl() + "/api/v1/datapoints");
log.info("posting metrics to kairos at: {}", this.uri);
try {
SSLContext ctx = new SSLContextBuilder()
.useProtocol("TLS")
.build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", new SSLConnectionSocketFactory(ctx,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER))
.build();
PoolingHttpClientConnectionManager conman = new PoolingHttpClientConnectionManager(registry);
this.client = HttpClientBuilder.create()
.setConnectionManager(conman)
.setMaxConnTotal(config.getKairosPostThreadsMax()) // connections == threads
.setMaxConnPerRoute(config.getKairosPostThreadsMax()) // connections == threads
.evictIdleConnections(60L, TimeUnit.SECONDS)
.evictExpiredConnections()
.build();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* 执行http请求
*
* @param getMethod
* @return
* @throws IOException
*/
@SuppressWarnings("deprecation")
private final HttpResponse executeHttpRequest(HttpGet getMethod, String host) throws Exception {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry registry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslsf)
.build();
HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setMaxConnPerRoute(50)
.setMaxConnTotal(100)
.setConnectionManager(httpClientConnectionManager)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
getMethod.setConfig(requestConfig);
HttpResponse response = httpClient.execute(getMethod);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpResponseStatus.OK.code() && statusCode != HttpResponseStatus.PARTIAL_CONTENT.code()) {
String result = EntityUtils.toString(response.getEntity());
throw new RuntimeException("return error !" + response.getStatusLine().getReasonPhrase() + ", " + result);
}
return response;
}
public HttpClientGenerator() {
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", buildSSLConnectionSocketFactory())
.build();
connectionManager = new PoolingHttpClientConnectionManager(reg);
connectionManager.setDefaultMaxPerRoute(100);
}
private static HttpClient createDefaultHttpClient() {
Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(schemeRegistry);
connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
/**
* httpclient��ʽ HTTP/HTTPS��ʼ��
*
* @param urlParam �������
* @param cerpath ����·��
* @return ����HTTPCLIENT����
*/
private CloseableHttpClient iniHttpClient(String urlParam, String cerpath) throws NoSuchAlgorithmException, KeyManagementException {
CloseableHttpClient httpclient;
urlParam = urlParam.trim();
if (urlParam.startsWith("http://")) {
httpclient = HttpClients.createDefault();
} else if (urlParam.startsWith("https://")) {
//�����ƹ���֤�ķ�ʽ����https����
SSLContext sslContext;
if (null == cerpath || "".equals(cerpath.trim())) {
LogUtil.APP.info("��ʼ����HTTPS������֤����...");
TrustManager[] trustManagers = {new MyX509TrustManager()};
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());
} else {
LogUtil.APP.info("��ʼ����HTTPS˫����֤����...");
String[] strcerpath = cerpath.split(";", -1);
HttpClientTools hct = new HttpClientTools();
sslContext = hct.sslContextKeyStore(strcerpath[0], strcerpath[1]);
}
// ����Э��http��https��Ӧ�Ĵ���socket���ӹ����Ķ���
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
// ������SSL���ӻ���֤����֤����Ϣ
// .register("https", new SSLConnectionSocketFactory(sslContext)).build();
// ����������֤
.register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connManager.setDefaultMaxPerRoute(1);
//�����Զ����httpclient����
httpclient = HttpClients.custom().setConnectionManager(connManager).build();
} else {
httpclient = HttpClients.createDefault();
}
return httpclient;
}
private void initCookieStore() {
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.getDefault();
Registry<CookieSpecProvider> cookieSpecReg = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.DEFAULT, new DefaultCookieSpecProvider(publicSuffixMatcher))
.register(CookieSpecs.STANDARD, new RFC6265CookieSpecProvider(publicSuffixMatcher)).build();
CookieStore cookieStore = new BasicCookieStore();
context = HttpClientContext.create();
context.setCookieSpecRegistry(cookieSpecReg);
context.setCookieStore(cookieStore);
}
@Override
protected Registry<ConnectionSocketFactory> registry() {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", buildSSLConnectionSocketFactory())
.build();
}
@Override
protected Registry<SchemeIOSessionStrategy> registry() {
return RegistryBuilder
.<SchemeIOSessionStrategy>create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", buildSSLIOSessionStrategy())
.build();
}
@VisibleForTesting
HTTPConnectionFactory(final Configurator config) {
Registry<ConnectionSocketFactory> registry = null;
try {
final Configurator cfg = config == null ? ConfigUtil.getConfigInfo(HTTPConnectionFactory.class) : config;
// if someone doesn't want keep alives...
if (!cfg.findBooleanEntry(CFG_HTTP_KEEPALIVE, DFLT_KEEPALIVE)) {
this.connReuseStrategy = NoConnectionReuseStrategy.INSTANCE;
}
this.maxConns = cfg.findIntEntry(CFG_HTTP_MAXCONNS, DFLT_MAXCONNS);
this.userAgent = cfg.findStringEntry(CFG_HTTP_AGENT, DEFAULT_HTTP_AGENT);
final SSLContext sslContext = build(cfg);
// mainly for using in test environments where cert name may not match host name
final HostnameVerifier v = cfg.findBooleanEntry(CFG_NOOP_VERIFIER, false) ? new NoopHostnameVerifier() : new DefaultHostnameVerifier();
registry =
RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, PlainConnectionSocketFactory.getSocketFactory())
.register(HTTPS, new SSLConnectionSocketFactory(sslContext, v)).build();
} catch (IOException | GeneralSecurityException ex) {
log.error("Error configuring HTTPConnectionFactory. The connection factory will use HTTP Client default settings", ex);
}
if (registry == null) {
this.connMan = new PoolingHttpClientConnectionManager();
} else {
this.connMan = new PoolingHttpClientConnectionManager(registry);
}
this.connMan.setMaxTotal(this.maxConns);
}
public CloseableHttpClient createSecureHttpClient() {
Registry<ConnectionSocketFactory> socketFactoryRegistry;
RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder = RegistryBuilder
.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory());
socketFactoryRegistryBuilder.register("https", createSslSocketFactory());
socketFactoryRegistry = socketFactoryRegistryBuilder.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
Objects.requireNonNull(socketFactoryRegistry));
return HttpClientBuilder.create().setConnectionManager(connectionManager).disableCookieManagement()
.disableAuthCaching().build();
}