@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; }
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); } }
@Override public void afterPropertiesSet() throws Exception { cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider> create().register("easy", new CookieSpecProvider() { public CookieSpec create(HttpContext context) { return new DefaultCookieSpec() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { } }; } }).build(); requestConfig = RequestConfig.custom().setCookieSpec("easy") .setConnectionRequestTimeout(propertyConfigurer.getIntValue("connection.request.timeout")) .setSocketTimeout(propertyConfigurer.getIntValue("socket_timeout")) .setConnectTimeout(propertyConfigurer.getIntValue("connection_timeout")).build(); }
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(); }
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(); }
@Override public void setUsernamePassword(AuthenticationType authType, String username, String password) { this.credentials = new UsernamePasswordCredentials( Objects.requireNonNull(username), Objects.requireNonNull(password)); this.credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create(); switch (authType) { case BASIC: authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); break; case DIGEST: authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; default: throw new IllegalArgumentException("Unsupported authentiation type: " + authType); } this.authRegistry = authRegistryBuilder.build(); }
public static HttpClient build(byte[] token) { HttpClientBuilder builder = HttpClientBuilder.create(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new CollaredSPNegoSchemeFactory(token)).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() { @Override public Principal getUserPrincipal() { return null; } @Override public String getPassword() { return null; } }); builder.setDefaultCredentialsProvider(credentialsProvider); return builder.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(); }
/** * 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(); }
/** * Creates a builder containing the default registry entries, using the provided public suffix matcher. */ public static RegistryBuilder<CookieSpecProvider> createDefaultBuilder(final PublicSuffixMatcher publicSuffixMatcher) { final CookieSpecProvider defaultProvider = new DefaultCookieSpecProvider(publicSuffixMatcher); final CookieSpecProvider laxStandardProvider = new RFC6265CookieSpecProvider( RFC6265CookieSpecProvider.CompatibilityLevel.RELAXED, publicSuffixMatcher); final CookieSpecProvider strictStandardProvider = new RFC6265CookieSpecProvider( RFC6265CookieSpecProvider.CompatibilityLevel.STRICT, publicSuffixMatcher); return RegistryBuilder.<CookieSpecProvider>create() .register(CookieSpecs.DEFAULT, defaultProvider) .register("best-match", defaultProvider) .register("compatibility", defaultProvider) .register(CookieSpecs.STANDARD, laxStandardProvider) .register(CookieSpecs.STANDARD_STRICT, strictStandardProvider) .register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider()) .register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider()); }
@Before public void setUp() { this.target = new HttpHost("localhost.local", 80); this.cookieStore = new BasicCookieStore(); final BasicClientCookie2 cookie1 = new BasicClientCookie2("name1", "value1"); cookie1.setVersion(1); cookie1.setDomain("localhost.local"); cookie1.setPath("/"); this.cookieStore.addCookie(cookie1); final BasicClientCookie2 cookie2 = new BasicClientCookie2("name2", "value2"); cookie2.setVersion(1); cookie2.setDomain("localhost.local"); cookie2.setPath("/"); this.cookieStore.addCookie(cookie2); this.cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create() .register(CookieSpecs.DEFAULT, new DefaultCookieSpecProvider()) .register(CookieSpecs.STANDARD, new RFC2965SpecProvider()) .register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider()) .register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider()) .build(); }
@Before public void setUp() throws Exception { this.defltAuthStrategy = Mockito.mock(AuthenticationStrategy.class); this.authState = new AuthState(); this.authScheme = Mockito.mock(ContextAwareAuthScheme.class); Mockito.when(this.authScheme.getSchemeName()).thenReturn("Basic"); Mockito.when(this.authScheme.isComplete()).thenReturn(Boolean.TRUE); this.context = new BasicHttpContext(); this.defaultHost = new HttpHost("localhost", 80); this.context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.defaultHost); this.credentials = Mockito.mock(Credentials.class); this.credentialsProvider = new BasicCredentialsProvider(); this.credentialsProvider.setCredentials(AuthScope.ANY, this.credentials); this.context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider); this.authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("basic", new BasicSchemeFactory()) .register("digest", new DigestSchemeFactory()) .register("ntlm", new NTLMSchemeFactory()).build(); this.context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry); this.authCache = Mockito.mock(AuthCache.class); this.context.setAttribute(HttpClientContext.AUTH_CACHE, this.authCache); this.httpAuthenticator = new HttpAuthenticator(); }
/** * Tests that the client will stop connecting to the server if * the server still keep asking for a valid ticket. */ @Test public void testDontTryToAuthenticateEndlessly() throws Exception { this.serverBootstrap.registerHandler("*", new PleaseNegotiateService()); final HttpHost target = start(); final AuthSchemeProvider nsf = new NegotiateSchemeProviderWithMockGssManager(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); final Credentials use_jaas_creds = new UseJaasCredentials(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, nsf) .build(); this.httpclient = HttpClients.custom() .setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credentialsProvider) .build(); final String s = "/path"; final HttpGet httpget = new HttpGet(s); final HttpResponse response = this.httpclient.execute(target, httpget); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
@Test public void testSelectNoCredentialsProvider() throws Exception { final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy(); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); final HttpHost authhost = new HttpHost("locahost", 80); final HttpClientContext context = HttpClientContext.create(); final Map<String, Header> challenges = new HashMap<String, Header>(); challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\"")); challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\"")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("basic", new BasicSchemeFactory()) .register("digest", new DigestSchemeFactory()).build(); context.setAuthSchemeRegistry(authSchemeRegistry); final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context); Assert.assertNotNull(options); Assert.assertEquals(0, options.size()); }
@Test public void testNoCredentials() throws Exception { final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy(); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); final HttpHost authhost = new HttpHost("locahost", 80); final HttpClientContext context = HttpClientContext.create(); final Map<String, Header> challenges = new HashMap<String, Header>(); challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"realm1\"")); challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm2\", nonce=\"1234\"")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("basic", new BasicSchemeFactory()) .register("digest", new DigestSchemeFactory()).build(); context.setAuthSchemeRegistry(authSchemeRegistry); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); context.setCredentialsProvider(credentialsProvider); final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context); Assert.assertNotNull(options); Assert.assertEquals(0, options.size()); }
private static HttpClientBuilder createBuilder() { if (isWinAuthAvailable()) { final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.NTLM, new WindowsNTLMSchemeFactory(null)) .register(AuthSchemes.SPNEGO, new WindowsNegotiateSchemeFactory(null)) .build(); final CredentialsProvider credsProvider = new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider()); return HttpClientBuilder.create() .setDefaultCredentialsProvider(credsProvider) .setDefaultAuthSchemeRegistry(authSchemeRegistry); } else { return HttpClientBuilder.create(); } }
private HttpClient getHttpClient() { Credentials use_jaas_creds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credsProvider).build(); return httpclient; }
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(); }
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final HttpClientBuilder hcb = HttpClients.custom(); if (useSpnego) { //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);// new NegotiateSchemeProvider(); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); } hcb.setDefaultCredentialsProvider(credsProvider); hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build()); final CloseableHttpClient httpClient = hcb.build(); return httpClient; }
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 void configureAuthSchemeRegistry(HttpClientBuilder builder) { builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()) .build() ); }