List of usage examples for org.apache.http.impl.client HttpClientBuilder setSSLSocketFactory
public final HttpClientBuilder setSSLSocketFactory(final LayeredConnectionSocketFactory sslSocketFactory)
From source file:com.threatconnect.sdk.conn.ConnectionUtil.java
/** * Adds the ability to trust self signed certificates for this HttpClientBuilder * /*w w w .ja v a 2s.c o m*/ * @param httpClientBuilder * the HttpClientBuilder to apply these settings to */ public static void trustSelfSignedCerts(final HttpClientBuilder httpClientBuilder) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { // allow all return true; } }); httpClientBuilder.setSSLSocketFactory(sslsf); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { logger.error("Error adding SSLSocketFactory to HttpClientBuilder", ex); } }
From source file:org.pepstock.jem.commands.util.HttpUtil.java
/** * Configures SSL in the parameter <code>httpClientBuilder</code>, if * necessary, that is if the <code>protocolType</code> is * {@link HttpResource#HTTPS_PROTOCOL}. <br> * If <code>port</code> is <code>null</code>, {@link #DEFAULT_HTTPS_PORT} is * used.// w w w .java 2 s .com * * @param httpClientBuilder http client builder already created in which to * set SSL property. * @param protocolType the protocol type: <li> * {@link HttpResource#HTTP_PROTOCOL} <li> * {@link HttpResource#HTTPS_PROTOCOL} * @throws KeyStoreException if an error occurs * @throws NoSuchAlgorithmException if an error occurs * @throws UnrecoverableKeyException if an error occurs * @throws KeyManagementException if an error occurs */ private static void configureSSL(HttpClientBuilder httpClientBuilder, String protocolType) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { // sets SSL ONLY if the scheme is HTTPS if (HttpResourceKeys.HTTPS_PROTOCOL.equalsIgnoreCase(protocolType)) { SSLConnectionSocketFactory sf = buildSSLConnectionSocketFactory(); httpClientBuilder.setSSLSocketFactory(sf); } }
From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java
/** * Because the creation of the SSLConnectionSocketFactory is expensive (reads from disk * the certs file) we will cache the client. The client is re-used so doesn't have any * target RTC server info associated with it. * @return an HttpClient/*from w w w.j av a 2 s .c o m*/ * @throws GeneralSecurityException */ private synchronized static CloseableHttpClient getClient() throws GeneralSecurityException { if (HTTP_CLIENT == null) { HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setSSLSocketFactory(getSSLConnectionSocketFactory()); // TODO to find out if this is sufficient, we can periodically dump the PoolStats clientBuilder.setMaxConnPerRoute(10); clientBuilder.setMaxConnTotal(100); // allow redirects on POST clientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); // How long to wait to get a connection from our connection manager. The default // timeouts are forever which is probably not good. // TODO If we set it when creating the GET, PUT & POST maybe its not really needed here RequestConfig config = getRequestConfig(CONNECTION_REQUEST_TIMEOUT); clientBuilder.setDefaultRequestConfig(config); // This will create a client with the defaults (which includes the PoolingConnectionManager) HTTP_CLIENT = clientBuilder.build(); } return HTTP_CLIENT; }
From source file:edu.emory.bmi.medicurator.tcia.TciaQuery.java
private HttpClient getInsecureClient() throws Exception { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }// w w w.j a v a2s . com }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setSSLSocketFactory(sslsf); if (Constants.PROXY_HOST != null && Constants.PROXY_PORT != null) { HttpHost proxy = new HttpHost(Constants.PROXY_HOST, Constants.PROXY_PORT, "http"); builder.setProxy(proxy); } if (Constants.PROXY_USERNAME != null && Constants.PROXY_PASSWORD != null) { Credentials credentials = new UsernamePasswordCredentials(Constants.PROXY_USERNAME, Constants.PROXY_PASSWORD); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, credentials); builder.setDefaultCredentialsProvider(credsProvider); } return builder.build(); }
From source file:org.obiba.mica.core.service.AgateRestService.java
protected HttpClient createHttpClient() { HttpClientBuilder builder = HttpClientBuilder.create(); try {//from w ww . ja va 2 s. c o m builder.setSSLSocketFactory(getSocketFactory()); // if component not specified, will use the default } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException(e); } return builder.build(); }
From source file:com.miapc.ipudong.Application.java
@Bean public RestTemplate getRestTemplate() { SSLContext sslcontext = null; Set<KeyManager> keymanagers = new LinkedHashSet<>(); Set<TrustManager> trustmanagers = new LinkedHashSet<>(); try {//www . ja v a2 s .c o m trustmanagers.add(new HttpsTrustManager()); KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]); TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]); sslcontext = SSLContexts.custom().build(); sslcontext.init(km, tm, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setSSLSocketFactory(factory); // ?3? httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true)); // ????Keep-Alive httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); List<Header> headers = new ArrayList<>(); headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36")); headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate")); headers.add(new BasicHeader("Accept-Language", "zh-CN")); headers.add(new BasicHeader("Connection", "Keep-Alive")); headers.add(new BasicHeader("Authorization", "reslibu")); httpClientBuilder.setDefaultHeaders(headers); CloseableHttpClient httpClient = httpClientBuilder.build(); if (httpClient != null) { // httpClient??RequestConfig HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); // clientHttpRequestFactory.setConnectTimeout(60 * 1000); // ???SocketTimeout clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000); // ???? clientHttpRequestFactory.setConnectionRequestTimeout(5000); // ?truePOSTPUT????false? // clientHttpRequestFactory.setBufferRequestBody(false); // ? List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new MappingJackson2XmlHttpMessageConverter()); RestTemplate restTemplate = new RestTemplate(messageConverters); restTemplate.setRequestFactory(clientHttpRequestFactory); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); return restTemplate; } else { return null; } }
From source file:com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigSettings.java
/** * Update the given {@link HttpClientBuilder} object with the appropriate * settings from configuration./*from w ww . j a v a 2 s . c om*/ * * @param httpClientBuilder * The object to update. * @return The updates httpClientBuilder */ public HttpClientBuilder applyConfig(HttpClientBuilder httpClientBuilder) { if (properties .containsKey(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)) { httpClientBuilder.setSSLSocketFactory((LayeredConnectionSocketFactory) properties .get(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)) { httpClientBuilder.setConnectionManager((HttpClientConnectionManager) properties .get(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI)) { httpClientBuilder.setProxy(new HttpHost( (String) properties.get(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI))); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)) { httpClientBuilder.setRetryHandler((HttpRequestRetryHandler) properties .get(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER)) { return (HttpClientBuilder) properties .get(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER); } if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY)) { httpClientBuilder.setRedirectStrategy((DefaultRedirectStrategy) properties .get(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY)); // Currently the redirect strategy, due to what seems to be a bug, // fails for post requests since it tries do double // add the content-length header. This workaround makes sure this header is always // removed before it is actually processed by apache httpClientBuilder.addInterceptorFirst(new HttpHeaderRemovalFilter()); } if (properties.containsKey("AuthFilter")) { @SuppressWarnings("unchecked") ServiceRequestFilter filter = (ServiceRequestFilter) properties.get("AuthFilter"); httpClientBuilder.addInterceptorFirst(new FilterInterceptor(filter)); } if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_HOST) && properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_PORT)) { String proxyHost = (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_HOST); int proxyPort = Integer .parseInt((String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_PORT)); HttpHost proxy; if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME)) { proxy = new HttpHost(proxyHost, proxyPort, (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME)); } else { proxy = new HttpHost(proxyHost, proxyPort); } httpClientBuilder.setProxy(proxy); } return httpClientBuilder; }
From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java
/** * @return Client that can use preemptive auth and self-signed certificates *//* ww w. j ava 2 s .co m*/ protected HttpClientBuilder clientBuilder() throws Exception { HttpClientBuilder builder = HttpClients.custom(); builder.setDefaultRequestConfig(requestConfig()); builder.setDefaultCredentialsProvider(credentialsProvider()); builder.setSSLSocketFactory(sslSocketFactory()); return builder; }
From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java
private static Tuple<AbstractReloadingMetadataResolver, Supplier<EntityDescriptor>> parseHttpMetadata( String metadataUrl, RealmConfig config, SSLService sslService) throws ResolverException, ComponentInitializationException, PrivilegedActionException { final String entityId = require(config, IDP_ENTITY_ID); HttpClientBuilder builder = HttpClientBuilder.create(); // ssl setup//w w w. jav a 2s .c om Settings sslSettings = config.settings().getByPrefix(SamlRealmSettings.SSL_PREFIX); boolean isHostnameVerificationEnabled = sslService.getVerificationMode(sslSettings, Settings.EMPTY) .isHostnameVerificationEnabled(); HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE; SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory( sslService.sslSocketFactory(sslSettings), verifier); builder.setSSLSocketFactory(factory); HTTPMetadataResolver resolver = new PrivilegedHTTPMetadataResolver(builder.build(), metadataUrl); TimeValue refresh = IDP_METADATA_HTTP_REFRESH.get(config.settings()); resolver.setMinRefreshDelay(refresh.millis()); resolver.setMaxRefreshDelay(refresh.millis()); initialiseResolver(resolver, config); return new Tuple<>(resolver, () -> { // for some reason the resolver supports its own trust engine and custom socket factories. // we do not use these as we'd rather rely on the JDK versions for TLS security! SpecialPermission.check(); try { return AccessController.doPrivileged( (PrivilegedExceptionAction<EntityDescriptor>) () -> resolveEntityDescriptor(resolver, entityId, metadataUrl)); } catch (PrivilegedActionException e) { throw ExceptionsHelper.convertToRuntime((Exception) ExceptionsHelper.unwrapCause(e)); } }); }