Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#setSSLSocketFactory()
The following examples show how to use
org.apache.http.impl.client.HttpClientBuilder#setSSLSocketFactory() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpEventPublisher.java From DataflowTemplates with Apache License 2.0 | 6 votes |
/** * Utility method to create a {@link CloseableHttpClient} to make http POSTs against Splunk's * HEC. * * @param maxConnections max number of parallel connections. * @param disableCertificateValidation should disable certificate validation. */ private CloseableHttpClient getHttpClient( int maxConnections, boolean disableCertificateValidation) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder(); if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) { LOG.info("SSL connection requested"); HostnameVerifier hostnameVerifier = disableCertificateValidation ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier(); SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); if (disableCertificateValidation) { LOG.info("Certificate validation is disabled"); sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true); } SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier); builder.setSSLSocketFactory(connectionSocketFactory); } builder.setMaxConnTotal(maxConnections); builder.setDefaultRequestConfig( RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()); return builder.build(); }
Example 2
Source File: TagMeAnnotator.java From gerbil with GNU Affero General Public License v3.0 | 6 votes |
protected void init() throws GerbilException { HttpClientBuilder builder = HttpManagement.getInstance().generateHttpClientBuilder(); try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream instream = this.getClass().getClassLoader().getResourceAsStream(KEY_STORE_RESOURCE_NAME); try { keyStore.load(instream, KEY_STORE_PASSWORD); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()) .build(); builder.setSSLContext(sslcontext); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); builder.setSSLSocketFactory(sslsf); CloseableHttpClient localClient = builder.build(); this.setClient(localClient); } catch (Exception e) { throw new GerbilException("Couldn't initialize SSL context.", e, ErrorTypes.ANNOTATOR_LOADING_ERROR); } this.setClient(builder.build()); }
Example 3
Source File: ClientHttpRequestFactoryFactory.java From spring-vault with Apache License 2.0 | 5 votes |
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration) throws GeneralSecurityException, IOException { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setRoutePlanner( new SystemDefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault())); if (hasSslConfiguration(sslConfiguration)) { SSLContext sslContext = getSSLContext(sslConfiguration, getTrustManagers(sslConfiguration)); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setSSLContext(sslContext); } RequestConfig requestConfig = RequestConfig.custom() // .setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis())) // .setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis())) // .setAuthenticationEnabled(true) // .build(); httpClientBuilder.setDefaultRequestConfig(requestConfig); // Support redirects httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); }
Example 4
Source File: ApacheCloudStackClient.java From apache-cloudstack-java-client with Apache License 2.0 | 5 votes |
/** * It creates an {@link CloseableHttpClient} object. * If {@link #validateServerHttpsCertificate} indicates that we should not validate HTTPS server certificate, we use an insecure SSL factory; the insecure factory is created using {@link #createInsecureSslFactory()}. */ protected CloseableHttpClient createHttpClient() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(createRequestConfig()); if (!validateServerHttpsCertificate) { SSLConnectionSocketFactory sslsf = createInsecureSslFactory(); httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); }
Example 5
Source File: HttpUtils.java From cms with Apache License 2.0 | 5 votes |
public static CloseableHttpClient getHttpClient(HttpProtocol protocol) { HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connMgr) .setDefaultRequestConfig(requestConfig); if (HttpProtocol.HTTPS.equals(protocol)) { builder.setSSLSocketFactory(createSSLSocketFactory()); } return builder.build(); }
Example 6
Source File: NexusITSupport.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
protected HttpClientBuilder clientBuilder(final URL nexusUrl, final boolean useCredentials) throws Exception { HttpClientBuilder builder = HttpClients.custom(); builder.setDefaultRequestConfig(requestConfig()); if (useCredentials) { doUseCredentials(nexusUrl, builder); } builder.setSSLSocketFactory(sslSocketFactory()); return builder; }
Example 7
Source File: VaultConfig.java From cloudbreak with Apache License 2.0 | 5 votes |
private ClientHttpRequestFactory usingHttpComponents(ClientOptions options, SslConfiguration sslConfiguration) throws GeneralSecurityException, IOException { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner( DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault())); if (isNoneEmpty(httpsProxyUser, httpsProxyPassword)) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(httpsProxyUser, httpsProxyPassword); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, credentials); httpClientBuilder.setDefaultCredentialsProvider(provider); } if (hasSslConfiguration(sslConfiguration)) { SSLContext sslContext = getSSLContext(sslConfiguration, getTrustManagers(sslConfiguration)); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContext); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setSSLContext(sslContext); } RequestConfig requestConfig = RequestConfig .custom() .setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis())) .setSocketTimeout(Math.toIntExact(options.getReadTimeout().toMillis())) .setAuthenticationEnabled(true) .build(); httpClientBuilder.setDefaultRequestConfig(requestConfig); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); }
Example 8
Source File: GoAgentServerHttpClientBuilder.java From gocd with Apache License 2.0 | 5 votes |
@Override public CloseableHttpClient build() throws Exception { HttpClientBuilder builder = HttpClients.custom(); builder.useSystemProperties(); builder .setDefaultSocketConfig(SocketConfig.custom() .setTcpNoDelay(true) .setSoKeepAlive(true) .build() ) .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE); HostnameVerifier hostnameVerifier = sslVerificationMode.verifier(); TrustStrategy trustStrategy = sslVerificationMode.trustStrategy(); KeyStore trustStore = agentTruststore(); SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); if (trustStore != null || trustStrategy != null) { sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy); } KeyStore keystore = agentKeystore(); if (keystore != null) { sslContextBuilder.loadKeyMaterial(keystore, agentKeystorePassword); } SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier); builder.setSSLSocketFactory(sslConnectionSocketFactory); return builder.build(); }
Example 9
Source File: DockerRepositoryServiceImpl.java From super-cloudops with Apache License 2.0 | 5 votes |
private HttpComponentsClientHttpRequestFactory generateHttpRequestFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setSSLSocketFactory(connectionSocketFactory); CloseableHttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(httpClient); return factory; }
Example 10
Source File: BaseTest.java From oxAuth with MIT License | 5 votes |
private static HttpClient createClient(SSLConnectionSocketFactory connectionFactory) { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); HttpClientBuilder httClientBuilder = HttpClients.custom(); if (connectionFactory != null) { httClientBuilder = httClientBuilder.setSSLSocketFactory(connectionFactory); } HttpClient httpClient = httClientBuilder .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()) .setConnectionManager(cm).build(); cm.setMaxTotal(200); // Increase max total connection to 200 cm.setDefaultMaxPerRoute(20); // Increase default max connection per route to 20 return httpClient; }
Example 11
Source File: HttpUtil.java From learnjavabug with MIT License | 5 votes |
public static String post(String url, String payload) throws UnsupportedEncodingException { HttpPost httpPost = new HttpPost(url); // httpPost.addHeader("Cookie", "rememberMe=" + Base64.getEncoder().encodeToString(data)); HttpEntity httpEntity = new StringEntity(payload, "application/x-www-form-urlencoded", "utf-8"); httpPost.setEntity(httpEntity); try { HttpClientBuilder httpClientBuilder = HttpClients .custom() // .setProxy(new HttpHost("127.0.0.1", 8080)) .disableRedirectHandling() // .disableCookieManagement() ; if (url.startsWith("https://")) { httpClientBuilder.setSSLSocketFactory(sslsf); } CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { httpClient = httpClientBuilder.build(); response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status == 200) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } } finally { response.close(); httpClient.close(); } } catch (Exception e) { e.printStackTrace(); } return null; }
Example 12
Source File: HttpClientHelper.java From herd with Apache License 2.0 | 5 votes |
/** * Creates a new HTTP client. * * @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate * @param disableHostnameVerification specifies whether to turn off hostname verification * * @return the HTTP client * @throws KeyStoreException if a key store exception occurs * @throws NoSuchAlgorithmException if a no such algorithm exception occurs * @throws KeyManagementException if key management exception */ public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate, Boolean disableHostnameVerification) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { // Create an HTTP client builder. HttpClientBuilder httpClientBuilder = HttpClients.custom(); // Create an SSL context builder. SSLContextBuilder sslContextBuilder = SSLContexts.custom(); // If specified, setup a trust strategy that allows all certificates. if (BooleanUtils.isTrue(trustSelfSignedCertificate)) { sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); } // If specified, turn hostname verification off. HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification) ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; // Create and assign an SSL connection socket factory. SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory); // Build and return an HTTP client. return httpClientBuilder.build(); }
Example 13
Source File: NexusITSupport.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
protected HttpClientBuilder clientBuilder(final URL nexusUrl, final boolean useCredentials) throws Exception { HttpClientBuilder builder = HttpClients.custom(); builder.setDefaultRequestConfig(requestConfig()); if (useCredentials) { doUseCredentials(nexusUrl, builder); } builder.setSSLSocketFactory(sslSocketFactory()); return builder; }
Example 14
Source File: WxPayServiceApacheHttpImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
private void initSSLContext(HttpClientBuilder httpClientBuilder) throws WxPayException { SSLContext sslContext = this.getConfig().getSslContext(); if (null == sslContext) { sslContext = this.getConfig().initSSLContext(); } SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, new DefaultHostnameVerifier()); httpClientBuilder.setSSLSocketFactory(connectionSocketFactory); }
Example 15
Source File: WxMpServiceImpl.java From weixin-java-tools with Apache License 2.0 | 5 votes |
public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) { this.wxMpConfigStorage = wxConfigProvider; String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host(); int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port(); String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username(); String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password(); final HttpClientBuilder builder = HttpClients.custom(); if (StringUtils.isNotBlank(http_proxy_host)) { // 使用代理服务器 if (StringUtils.isNotBlank(http_proxy_username)) { // 需要用户认证的代理服务器 CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(http_proxy_host, http_proxy_port), new UsernamePasswordCredentials(http_proxy_username, http_proxy_password)); builder .setDefaultCredentialsProvider(credsProvider); } else { // 无需用户认证的代理服务器 } httpProxy = new HttpHost(http_proxy_host, http_proxy_port); } if (wxConfigProvider.getSSLContext() != null){ SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( wxConfigProvider.getSSLContext(), new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(sslsf); } httpClient = builder.build(); }
Example 16
Source File: SslTrusted.java From verano-http with MIT License | 5 votes |
@Override public final HttpClientBuilder apply(final HttpClientBuilder builder) { final SSLContext context; try { final SSLContextBuilder ssl = SSLContexts.custom(); ssl.loadTrustMaterial((chain, type) -> true); context = ssl.build(); //@checkstyle IllegalCatchCheck (1 lines) } catch (final Exception exp) { throw new IllegalStateException(exp); } return builder.setSSLSocketFactory( new SSLConnectionSocketFactory(context, (ctx, session) -> true) ); }
Example 17
Source File: DatabricksRestClientImpl.java From databricks-rest-client with Apache License 2.0 | 4 votes |
protected void initClient(DatabricksServiceFactory.Builder builder) { HttpClientBuilder clientBuilder = HttpClients.custom().useSystemProperties() .setRetryHandler(retryHandler) .setServiceUnavailableRetryStrategy(retryStrategy) .setDefaultRequestConfig(createRequestConfig(builder)); List<Header> headers = new ArrayList<>(); if (isNotEmpty(builder.getToken())) { Header authHeader = new BasicHeader("Authorization", String.format("Bearer %s", builder.getToken())); headers.add(authHeader); } else { // password authorization CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(host, HTTPS_PORT), new UsernamePasswordCredentials(builder.getUsername(), builder.getPassword())); clientBuilder.setDefaultCredentialsProvider(credsProvider); } String userAgent = builder.getUserAgent(); if (userAgent != null && userAgent.length() > 0) { Header userAgentHeader = new BasicHeader("User-Agent", userAgent); headers.add(userAgentHeader); } if (!headers.isEmpty()) { clientBuilder.setDefaultHeaders(headers); } try { SSLContext ctx = SSLContext.getDefault(); // Allow TLSv1.2 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( ctx, new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); clientBuilder = clientBuilder.setSSLSocketFactory(sslsf); } catch (Exception e) { logger.error("", e); } client = clientBuilder.build(); //CloseableHttpClient url = String.format("https://%s/api/%s", host, apiVersion); mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); }
Example 18
Source File: JolokiaClientFactory.java From hawkular-agent with Apache License 2.0 | 4 votes |
@Override public void authenticate(HttpClientBuilder pBuilder, String pUser, String pPassword) { pBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)); super.authenticate(pBuilder, pUser, pPassword); }
Example 19
Source File: DefaultHttpClientFactory.java From knox with Apache License 2.0 | 4 votes |
@Override public HttpClient createHttpClient(FilterConfig filterConfig) { final String serviceRole = filterConfig.getInitParameter(PARAMETER_SERVICE_ROLE); HttpClientBuilder builder; GatewayConfig gatewayConfig = (GatewayConfig) filterConfig.getServletContext().getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE); GatewayServices services = (GatewayServices) filterConfig.getServletContext() .getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE); if (gatewayConfig != null && gatewayConfig.isMetricsEnabled()) { MetricsService metricsService = services.getService(ServiceType.METRICS_SERVICE); builder = metricsService.getInstrumented(HttpClientBuilder.class); } else { builder = HttpClients.custom(); } // Conditionally set a custom SSLContext SSLContext sslContext = createSSLContext(services, filterConfig, serviceRole); if(sslContext != null) { builder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)); } if (Boolean.parseBoolean(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UseJaasCredentials()); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true)) .build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCookieStore(new HadoopAuthCookieStore(gatewayConfig)) .setDefaultCredentialsProvider(credentialsProvider); } else { builder.setDefaultCookieStore(new NoCookieStore()); } builder.setKeepAliveStrategy( DefaultConnectionKeepAliveStrategy.INSTANCE ); builder.setConnectionReuseStrategy( DefaultConnectionReuseStrategy.INSTANCE ); builder.setRedirectStrategy( new NeverRedirectStrategy() ); builder.setRetryHandler( new NeverRetryHandler() ); int maxConnections = getMaxConnections( filterConfig ); builder.setMaxConnTotal( maxConnections ); builder.setMaxConnPerRoute( maxConnections ); builder.setDefaultRequestConfig(getRequestConfig(filterConfig, serviceRole)); // See KNOX-1530 for details builder.disableContentCompression(); return builder.build(); }
Example 20
Source File: SamlHTTPMetadataResolver.java From deprecated-security-advanced-modules with Apache License 2.0 | 3 votes |
private static HttpClient createHttpClient0(Settings settings, Path configPath) throws Exception { HttpClientBuilder builder = HttpClients.custom(); builder.useSystemProperties(); SettingsBasedSSLConfigurator.SSLConfig sslConfig = getSSLConfig(settings, configPath); if (sslConfig != null) { builder.setSSLSocketFactory(sslConfig.toSSLConnectionSocketFactory()); } return builder.build(); }