下面列出了怎么用org.apache.http.conn.socket.PlainConnectionSocketFactory的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();
}
/**
* Creates a special SSLContext using a custom TLS version and a set of ciphers enabled to process SSL connections.
* @param tlsVersion TLS version, for example TLSv1.2
* @param ciphers Set of ciphers used to create connections.
*/
public static CloseableHttpClient createHttpClient(String tlsVersion, String[] ciphers) {
try {
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext,
new String[] { tlsVersion }, ciphers, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslConnectionFactory)
.register("http", new PlainConnectionSocketFactory())
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
return HttpClients.custom()
.setSSLContext(sslContext)
.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
.setConnectionManager(cm)
.build();
} catch (Exception e) {
log.error("Error creating HttpClient with a custom TLS version and custom ciphers", e);
return null;
}
}
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);
}
}
public static void enabledSSL() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new PlainConnectionSocketFactory())
.register("https", sslConnectionSocketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(100);
client = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.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;
}
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
SSLContext sslContext = org.apache.http.ssl.SSLContexts.createDefault();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory)
.build();
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
new UsernamePasswordCredentials(username, password));
return HttpClientBuilder.create()
.setConnectionManager(new PoolingHttpClientConnectionManager(registry))
.setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
.setDefaultCredentialsProvider(credentialsProvider)
.build();
}
/**
* Gets an HTTP client that can be used to make requests.
*
* @return HTTP client
*/
public CloseableHttpClient getHttpClient(boolean ignoreSSL) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
if (ignoreSSL) {
final SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true)
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build()
);
return HttpClientBuilder.create()
.setSSLContext(sslContext)
.setConnectionManager(connectionManager)
.build();
}
return HttpClients.createDefault();
}
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(connectionManager)
.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
private static CloseableHttpClient getHttpClient() throws
KeyManagementException, NoSuchAlgorithmException,
KeyStoreException {
// Relax SSL Certificate check
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
return true;
}
}).build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder
.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE)).build();
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(registry);
return HttpClients.custom().setConnectionManager(connectionManager)
.build();
}
/**
* custom http client for server with SSL errors
*
* @return
*/
public final CloseableHttpClient getCustomClient() {
try {
HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
(TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
builder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
builder.setConnectionManager(connMgr);
return builder.build();
} catch (Exception ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
return getSystemClient();
}
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();
}
public HttpHelper(){
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setMaxConnPerRoute(50);
builder.setMaxConnTotal(100);
// 创建支持忽略证书的https
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
httpclient = HttpClientBuilder.create()
.setSSLContext(sslContext)
.setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build()))
.build();
} catch (Throwable e) {
// ignore
}
}
private PoolingHttpClientConnectionManager getConnectionManager()
throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
RegistryBuilder<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory());
if (properties.getSsl()) {
HostnameVerifier verifier = "strict".equals(properties.getSslMode()) ? SSLConnectionSocketFactory.getDefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE;
registry.register("https", new SSLConnectionSocketFactory(getSSLContext(), verifier));
}
//noinspection resource
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
registry.build(),
null,
null,
new IpVersionPriorityResolver(),
properties.getTimeToLiveMillis(),
TimeUnit.MILLISECONDS
);
connectionManager.setDefaultMaxPerRoute(properties.getDefaultMaxPerRoute());
connectionManager.setMaxTotal(properties.getMaxTotal());
connectionManager.setDefaultConnectionConfig(getConnectionConfig());
return connectionManager;
}
private void init() {
final URI originalUri = URI.create(DEFAULT_UNIX_ENDPOINT);
sanitizeUri = UnixFactory.sanitizeUri(originalUri);
final RegistryBuilder<ConnectionSocketFactory> registryBuilder =
RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("unix", new UnixFactory(originalUri));
final PoolingHttpClientConnectionManager cm =
new PoolingHttpClientConnectionManager(registryBuilder.build());
final RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout((int) SECONDS.toMillis(5))
.setConnectTimeout((int) SECONDS.toMillis(5))
.setSocketTimeout((int) SECONDS.toMillis(30))
.build();
final ClientConfig config = new ClientConfig()
.connectorProvider(new ApacheConnectorProvider())
.property(ApacheClientProperties.CONNECTION_MANAGER, cm)
.property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);
client = ClientBuilder.newBuilder().withConfig(config).build();
}
private Registry<ConnectionSocketFactory> registry(final HttpObjectConfig config) {
final ProxyInfo proxyInfo = config.getExecution().getProxyInfo();
final boolean isSocksProxied = (proxyInfo != null && proxyInfo.getProxy().type() == Proxy.Type.SOCKS);
if (isSocksProxied) {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new SocksHttp(proxyInfo.getProxy()))
.register("https", new SocksHttps(proxyInfo.getProxy(), sslContext(config),
config.getExecution().getHostnameVerifier()))
.build();
} else {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext(config), config.getExecution().getHostnameVerifier()))
.build();
}
}
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();
}
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();
}
public static HttpClientConnectionManager createHttpClientConnectionManager(final Client client)
throws GeneralSecurityException, IOException {
final Connections connections = client.getConnections();
final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(createSSLContext(client)))
.build(),
null, // connection factory
null, // scheme port resolver
null, // dns resolver
connections.getTimeToLive().getAmount(),
connections.getTimeToLive().getUnit());
manager.setMaxTotal(connections.getMaxTotal());
manager.setDefaultMaxPerRoute(connections.getMaxPerRoute());
return manager;
}
private DefaultHttpTransport(ServiceCombSSLProperties serviceCombSSLProperties) {
SSLContext sslContext = SecretUtil.getSSLContext(serviceCombSSLProperties);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(DealHeaderUtil.CONNECT_TIMEOUT)
.setConnectionRequestTimeout(
DealHeaderUtil.CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(DealHeaderUtil.SOCKET_TIMEOUT).build();
//register http/https socket factory
Registry<ConnectionSocketFactory> connectionSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",
new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build();
//connection pool management
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
connectionSocketFactoryRegistry);
connectionManager.setMaxTotal(DealHeaderUtil.MAX_TOTAL);
connectionManager.setDefaultMaxPerRoute(DealHeaderUtil.DEFAULT_MAX_PER_ROUTE);
// construct httpClient
// delete before code : setSSLHostnameVerifier(hostnameVerifier)
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().
setDefaultRequestConfig(config).
setConnectionManager(connectionManager).
disableCookieManagement();
this.httpClient = httpClientBuilder.build();
}
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;
}
@Override
protected Registry<ConnectionSocketFactory> registry() {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", buildSSLConnectionSocketFactory())
.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);
}