@PostConstruct public void afterPropertiesSet() throws Exception { RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create(); schemeRegistry.register("http", PlainConnectionSocketFactory.getSocketFactory()); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(new KeyManager[0], new TrustManager[]{new SimpleTrustManager()}, null); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext); schemeRegistry.register("https", sf); pool = new PoolingHttpClientConnectionManager(schemeRegistry.build()); pool.setMaxTotal(maxConnection); pool.setDefaultMaxPerRoute(maxConnection); pool.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(sotimeout).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 void upgrade( final ManagedHttpClientConnection conn, final HttpHost host, final HttpContext context) throws IOException { final HttpClientContext clientContext = HttpClientContext.adapt(context); final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(clientContext); final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); if (sf == null) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported"); } if (!(sf instanceof LayeredConnectionSocketFactory)) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol does not support connection upgrade"); } final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf; Socket sock = conn.getSocket(); final int port = this.schemePortResolver.resolve(host); sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context); conn.bind(sock); }
private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException { try { KeyStore keyStore = KeyStoreUtils.createDockerKeyStore(certPath); SSLContext sslContext = SSLContexts.custom() .useTLS() .loadKeyMaterial(keyStore, "docker".toCharArray()) .loadTrustMaterial(keyStore) .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); return RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build(); } catch (GeneralSecurityException e) { throw new IOException(e); } }
public void init() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); /* 配置同时支持 HTTP 和 HTPPS */ Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build(); /* 初始化连接管理器 */ poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); poolConnManager.setMaxTotal(maxTotal); poolConnManager.setDefaultMaxPerRoute(defaultMaxPerRoute); requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout) .setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build(); httpClient = getConnection(); log.info("HttpConnectionManager初始化完成..."); } catch (Exception e) { log.error("error", e); } }
public static String httpsGet(String getUrl, String defaultCharset, Map<String, String> headerParas) throws KeyManagementException, NoSuchAlgorithmException { // 采用绕过验证的方式处理https请求 SSLContext sslcontext = createIgnoreVerifySSL(); // 设置协议http和https对应的处理socket链接工厂的对象 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager); // 创建自定义的httpclient对象 CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).build(); return getInner(getUrl, defaultCharset, headerParas, httpclient); }
private void initPoolingHttpClientManager () { final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", SSLConnectionSocketFactory.getSocketFactory()) .register("http", PlainConnectionSocketFactory.getSocketFactory()).build(); final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(MAX_CONNECTION); connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT) .setConnectionRequestTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT); final RequestConfig requestConfig = requestConfigBuilder.build(); HashSet<Header> defaultHeaders = new HashSet<Header>(); defaultHeaders.add(new BasicHeader(HttpHeaders.PRAGMA, "no-cache")); defaultHeaders.add(new BasicHeader(HttpHeaders.CACHE_CONTROL, "no-cache")); final HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(defaultHeaders).disableAuthCaching().disableContentCompression(); this.httpClient = httpClientBuilder.setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).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(); }
public HttpClientConnectionManager create(ApacheSdkHttpClientFactory configuration, AttributeMap standardOptions) { ConnectionSocketFactory sslsf = getPreferredSocketFactory(standardOptions); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( createSocketFactoryRegistry(sslsf), null, DefaultSchemePortResolver.INSTANCE, null, configuration.connectionTimeToLive().orElse(Defaults.CONNECTION_POOL_TTL).toMillis(), TimeUnit.MILLISECONDS); cm.setDefaultMaxPerRoute(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS)); cm.setMaxTotal(standardOptions.get(SdkHttpConfigurationOption.MAX_CONNECTIONS)); cm.setDefaultSocketConfig(buildSocketConfig(standardOptions)); return cm; }
@Override public HttpClientConnectionManager create(final HttpClientSettings settings) { ConnectionSocketFactory sslsf = getPreferredSocketFactory(settings); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( createSocketFactoryRegistry(sslsf), null, DefaultSchemePortResolver.INSTANCE, new DelegatingDnsResolver(settings.getDnsResolver()), settings.getConnectionPoolTTL(), TimeUnit.MILLISECONDS); cm.setValidateAfterInactivity(settings.getValidateAfterInactivityMillis()); cm.setDefaultMaxPerRoute(settings.getMaxConnections()); cm.setMaxTotal(settings.getMaxConnections()); cm.setDefaultSocketConfig(buildSocketConfig(settings)); cm.setDefaultConnectionConfig(buildConnectionConfig(settings)); return cm; }
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(); }
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(); }
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(); }
/** * Creates a new configured instance of {@link CloseableHttpClient} based * on the factory's configuration. * * @return new connection object instance */ public CloseableHttpClient createConnection() { final ConnectionSocketFactory socketFactory = new CloudApiSSLConnectionSocketFactory(config); final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create(); final Registry<ConnectionSocketFactory> socketFactoryRegistry = registryBuilder .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", socketFactory) .build(); final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, DNS_RESOLVER); httpClientBuilder.setConnectionManager(connectionManager); return httpClientBuilder.build(); }
public SimpleHttpClient(final SSLContext sslContext, final int listenPort, final boolean useCompression) { HttpClientBuilder builder = HttpClientBuilder.create(); if (!useCompression) { builder.disableContentCompression(); } if (sslContext != null) { SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 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; }
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 void initInsecureSslHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build(); httpClientBuilder.setSslcontext(sslContext); HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); insecureSslClient = httpClientBuilder.build(); }
protected HttpClientConnectionManager createConnectionManager(Registry<ConnectionSocketFactory> registry, int maxTotalConnections, int connectionsPerRoute) { // setup the connection live time PoolingHttpClientConnectionManager answer = new PoolingHttpClientConnectionManager(registry, null, null, null, getConnectionTimeToLive(), TimeUnit.MILLISECONDS); int localMaxTotalConnections = maxTotalConnections; if (localMaxTotalConnections == 0) { localMaxTotalConnections = getMaxTotalConnections(); } if (localMaxTotalConnections > 0) { answer.setMaxTotal(localMaxTotalConnections); } int localConnectionsPerRoute = connectionsPerRoute; if (localConnectionsPerRoute == 0) { localConnectionsPerRoute = getConnectionsPerRoute(); } if (localConnectionsPerRoute > 0) { answer.setDefaultMaxPerRoute(localConnectionsPerRoute); } LOG.info("Created ClientConnectionManager " + answer); return answer; }
@Override public void upgrade( final ManagedHttpClientConnection conn, final HttpHost host, final HttpContext context) throws IOException { final HttpClientContext clientContext = HttpClientContext.adapt(context); final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(clientContext); final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); if (sf == null) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported"); } if (!(sf instanceof LayeredConnectionSocketFactory)) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol does not support connection upgrade"); } final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf; Socket sock = conn.getSocket(); final int port = this.schemePortResolver.resolve(host); sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context); conn.bind(sock); }
public HttpClientBuilder getAzureClientBuilder() throws CloudException { try { //boolean disableSSLValidation = isSSLValidationDisabled(); boolean disableSSLValidation = true; HttpClientBuilder builder = HttpClientBuilder.create(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", new AzureSSLSocketFactory(new AzureX509(this), disableSSLValidation)) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); connManager.setMaxTotal(200); connManager.setDefaultMaxPerRoute(20); builder.setConnectionManager(connManager); return builder; } catch (Exception e) { throw new CloudException(e.getMessage()); } }
/** * This code sets up the httpclient to accept any SSL certificate. The * SSL certificate generated by the instructions above is not correctly * signed, so we need ignore the problem. * This code should not, under any circumstances, be allowed anywhere * the production code. * @return */ private CloseableHttpClient createClient () { try { HttpClientBuilder builder = HttpClientBuilder.create(); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[]{getTrustManager()}, null); SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(ctx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(scsf); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", scsf) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(ccm); return builder.build(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
public static Registry<ConnectionSocketFactory> getSchemeRegistry(final DockerCertificates dc) { final SSLConnectionSocketFactory https; if (dc == null) { https = SSLConnectionSocketFactory.getSocketFactory(); } else { https = new SSLConnectionSocketFactory(dc.sslContext(), dc.hostnameVerifier()); } final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder .<ConnectionSocketFactory>create() .register("https", https) .register("http", PlainConnectionSocketFactory.getSocketFactory()); return registryBuilder.build(); }
public OAuthHttpClient(int maxConnection, int connectTimeout, int socketTimeout) { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()) .build()); // set max connection connectionManager.setMaxTotal(maxConnection); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connectTimeout) .setSocketTimeout(socketTimeout) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .build(); httpClient = HttpClientBuilder.create() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) .build(); }
private CloseableHttpClient createSslHttpClient() throws Exception { final SSLContextBuilder wsBuilder = new SSLContextBuilder(); wsBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wsBuilder.build(), new AllowAllHostnameVerifier()); //This winds up using a PoolingHttpClientConnectionManager so need to pass the //RegistryBuilder final Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory> create().register("https", sslsf) .build(); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); return HttpClients .custom() .setConnectionManager(cm) .build(); }
public DWServerConnection(DWSettingsProvider settingsProvider) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { this.settingsProvider = settingsProvider; // SSLContextFactory to allow all hosts. Without this an SSLException is thrown with self signed certs SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(200); connectionManager.setDefaultMaxPerRoute(20); client = HttpClients.custom() .setConnectionManager(connectionManager) .build(); context = new HttpClientContext(); context.setCredentialsProvider(getCredientials()); }
private static CloseableHttpClient createInsecureSslHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { final SSLContext sslContext = new SSLContextBuilder() .useProtocol(INSECURE_SSL_PROTOCOL) .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf) .build(); final HttpClientConnectionManager connectionManager = createConnectionManager(socketFactoryRegistry); return HttpClients.custom() .setConnectionManager(connectionManager) .setSSLSocketFactory( sslsf).build(); }
private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception { HttpClientBuilder b = HttpClientBuilder.create(); // setup a Trust Strategy that allows all certificates. // SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build(); b.setSSLContext(sslContext); // here's the special part: // -- need to create an SSL Socket Factory, to use our weakened "trust strategy"; // -- and create a Registry, to register it. // SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, (s, sslSession) -> true); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); // now, we create connection-manager using our Registry. // -- allows multi-threaded use b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry)); return b; }
/** * @return the http connection manager. */ @Bean(destroyMethod = "shutdown") public PoolingHttpClientConnectionManager getConnectionManager() { // fallback to default implementation if (sslSocketFactory == null) { sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); } PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(RegistryBuilder .<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory).build()); connectionManager.setMaxTotal(maxPoolSize); connectionManager.setDefaultMaxPerRoute(maxPerRoute); return connectionManager; }
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(); }
private CloseableHttpClient createHttpClient() { try { final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .build(); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(managementClient.getMgmtAddress(), managementClient.getMgmtPort()), new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD)); return HttpClientBuilder.create() .setConnectionManager(new PoolingHttpClientConnectionManager(registry)) .setDefaultCredentialsProvider(credsProvider) .build(); } catch (Exception e) { throw new RuntimeException(e); } }
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) { try { SSLContext sslContext = SSLContexts.createDefault(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionSocketFactory) .register("http", PlainConnectionSocketFactory.getSocketFactory()) .build(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST), new UsernamePasswordCredentials(username, password)); PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry); HttpClientBuilder.create().setConnectionManager(connectionPool).build(); return HttpClientBuilder.create() .setConnectionManager(connectionPool) .setRetryHandler(new StandardHttpRequestRetryHandler(5, true)) .setDefaultCredentialsProvider(credsProvider).build(); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Create connection manager for http client. * * @return The connection manager for http client. */ private HttpClientConnectionManager createHttpClientConnectionManager() { ConnectionSocketFactory socketFactory = PlainConnectionSocketFactory.getSocketFactory(); LayeredConnectionSocketFactory sslSocketFactory; try { sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(), SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException e) { throw new BceClientException("Fail to create SSLConnectionSocketFactory", e); } Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register(Protocol.HTTP.toString(), socketFactory) .register(Protocol.HTTPS.toString(), sslSocketFactory).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections()); connectionManager .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(this.config.getSocketTimeoutInMillis()) .setTcpNoDelay(true).build()); connectionManager.setMaxTotal(this.config.getMaxConnections()); return connectionManager; }
private HttpClient getHttpClient() throws NoSuchAlgorithmException { // Ignores invalid certificate requests Registry<ConnectionSocketFactory> registry = getSchemeRegistry(); // Default connection manager PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_ROUTE); // Default request config RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_CON).setConnectTimeout(TIMEOUT_CON) .setSocketTimeout(TIMEOUT_SO).build(); return HttpClientBuilder.create().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build(); }
private static CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int maxRoute, 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); // 请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }; CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; }
public HttpConnectionPoolBuilder(final Host host, final ConnectionSocketFactory socketFactory, final ConnectionSocketFactory sslSocketFactory, final ProxyFinder proxyFinder) { this.host = host; this.socketFactory = socketFactory; this.sslSocketFactory = sslSocketFactory; this.proxyFinder = proxyFinder; }
public PoolingHttpClientConnectionManager createConnectionManager(final Registry<ConnectionSocketFactory> registry) { if(log.isDebugEnabled()) { log.debug(String.format("Setup connection pool with registry %s", registry)); } final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry); manager.setMaxTotal(preferences.getInteger("http.connections.total")); manager.setDefaultMaxPerRoute(preferences.getInteger("http.connections.route")); manager.setValidateAfterInactivity(5000); return manager; }
/** * 创建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) { } }