List of usage examples for org.apache.http.impl.client HttpClientBuilder setSSLSocketFactory
public final HttpClientBuilder setSSLSocketFactory(final LayeredConnectionSocketFactory sslSocketFactory)
From source file:com.liferay.sync.engine.session.Session.java
public static HttpClientBuilder createHttpClientBuilder(boolean trustSelfSigned, int maxConnections) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.disableAutomaticRetries(); RequestConfig.Builder builder = RequestConfig.custom(); builder.setConnectTimeout(PropsValues.SYNC_HTTP_CONNECTION_TIMEOUT); if (maxConnections == Integer.MAX_VALUE) { builder.setSocketTimeout(PropsValues.SYNC_HTTP_SOCKET_TIMEOUT * 2); } else {/*from w ww. j ava 2 s. co m*/ builder.setSocketTimeout(PropsValues.SYNC_HTTP_SOCKET_TIMEOUT); } List<Header> headers = new ArrayList<>(2); Header syncBuildHeader = new BasicHeader("Sync-Build", String.valueOf(ReleaseInfo.getBuildNumber())); headers.add(syncBuildHeader); String syncDeviceType = null; if (OSDetector.isApple()) { syncDeviceType = "desktop-mac"; } else if (OSDetector.isLinux()) { syncDeviceType = "desktop-linux"; } else if (OSDetector.isWindows()) { syncDeviceType = "desktop-windows"; } Header syncDeviceTypeHeader = new BasicHeader("Sync-Device", syncDeviceType); headers.add(syncDeviceTypeHeader); httpClientBuilder.setDefaultHeaders(headers); httpClientBuilder.setDefaultRequestConfig(builder.build()); httpClientBuilder.setMaxConnPerRoute(maxConnections); httpClientBuilder.setMaxConnTotal(maxConnections); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClientBuilder.setRoutePlanner(getHttpRoutePlanner()); try { if (trustSelfSigned) { httpClientBuilder.setSSLSocketFactory(_getTrustingSSLSocketFactory()); } else { httpClientBuilder.setSSLSocketFactory(_getDefaultSSLSocketFactory()); } } catch (Exception e) { _logger.error(e.getMessage(), e); } return httpClientBuilder; }
From source file:com.xebialabs.overthere.winrm.WinRmClient.java
private void configureTrust(final HttpClientBuilder httpclientBuilder) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { if (!"https".equalsIgnoreCase(targetURL.getProtocol())) { return;//from w w w . ja v a 2s . c om } final TrustStrategy trustStrategy = httpsCertTrustStrategy.getStrategy(); SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(trustStrategy).build(); final HostnameVerifier hostnameVerifier = httpsHostnameVerifyStrategy.getVerifier(); final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); httpclientBuilder.setSSLSocketFactory(socketFactory); }
From source file:com.clustercontrol.http.util.GetHttpResponse.java
private CloseableHttpClient getHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { if (m_client == null) { List<Header> headers = new ArrayList<>(); HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(m_cledentialProvider) .setDefaultHeaders(headers); if (!this.m_needAuthSSLCert) { // SSL ?? TrustStrategy trustStrategy = new TrustStrategy() { @Override//from w w w . j a v a 2 s.c o m public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; builder.setSSLSocketFactory(new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(), new NoopHostnameVerifier())); } RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .setConnectTimeout(m_connectTimeout).setSocketTimeout(m_requestTimeout).build(); builder.setDefaultRequestConfig(requestConfig); if (m_proxyHost != null) { HttpHost proxy = new HttpHost(m_proxyHost, m_proxyPort, m_proxyScheme == null ? "https" : m_proxyScheme); if (m_proxyUser != null && m_proxyPassword != null) { m_cledentialProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()), new UsernamePasswordCredentials(m_proxyUser, m_proxyPassword)); } builder.setProxy(proxy); } if (m_userAgent != null) { headers.add(new BasicHeader(HTTP.USER_AGENT, m_userAgent)); } if (m_cancelProxyCache) { // ? // https://www.ipa.go.jp/security/awareness/vendor/programmingv2/contents/405.html headers.add(new BasicHeader("Cache-Control", "no-cache")); headers.add(new BasicHeader("Pragma", "no-cache")); } if (keepAlive) { headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); } else { headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); } m_client = builder.build(); } return m_client; }
From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java
/** * Set up http client with credentials/*from w w w .j av a 2 s . c o m*/ * @return Http client * @throws MojoExecutionException Mojo execution exception */ protected final CloseableHttpClient getHttpClient() throws MojoExecutionException { try { URI crxUri = new URI(getCrxPackageManagerUrl()); final AuthScope authScope = new AuthScope(crxUri.getHost(), crxUri.getPort()); final Credentials credentials = new UsernamePasswordCredentials(this.userId, this.password); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(authScope, credentials); HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { // enable preemptive authentication AuthState authState = (AuthState) context .getAttribute(HttpClientContext.TARGET_AUTH_STATE); authState.update(new BasicScheme(), credentials); } }); if (this.relaxedSSLCheck) { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); } catch (URISyntaxException ex) { throw new MojoExecutionException("Invalid url: " + getCrxPackageManagerUrl(), ex); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex) { throw new MojoExecutionException("Could not set relaxedSSLCheck", ex); } }
From source file:groovyx.net.http.ApacheHttpBuilder.java
/** * Creates a new `HttpBuilder` based on the Apache HTTP client. While it is acceptable to create a builder with this method, it is generally * preferred to use one of the `static` `configure(...)` methods. * * @param config the configuration object */// w w w.j a v a 2 s .co m public ApacheHttpBuilder(final HttpObjectConfig config) { super(config); this.proxyInfo = config.getExecution().getProxyInfo(); this.config = new HttpConfigs.ThreadSafeHttpConfig(config.getChainedConfig()); this.executor = config.getExecution().getExecutor(); this.clientConfig = config.getClient(); final HttpClientBuilder myBuilder = HttpClients.custom(); final Registry<ConnectionSocketFactory> registry = registry(config); if (config.getExecution().getMaxThreads() > 1) { final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(config.getExecution().getMaxThreads()); cm.setDefaultMaxPerRoute(config.getExecution().getMaxThreads()); myBuilder.setConnectionManager(cm); } else { final BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry); myBuilder.setConnectionManager(cm); } final SSLContext sslContext = config.getExecution().getSslContext(); if (sslContext != null) { myBuilder.setSSLContext(sslContext); myBuilder.setSSLSocketFactory( new SSLConnectionSocketFactory(sslContext, config.getExecution().getHostnameVerifier())); } myBuilder.addInterceptorFirst((HttpResponseInterceptor) (response, context) -> { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); final Consumer<Object> clientCustomizer = clientConfig.getClientCustomizer(); if (clientCustomizer != null) { clientCustomizer.accept(myBuilder); } this.client = myBuilder.build(); }
From source file:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java
private HttpClient getClient() { if (client == null) { HttpClientBuilder clientBuilder = HttpClients.custom(); RequestConfig.Builder configBuilder = RequestConfig.custom(); if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) { isUsingProxy = true;/*w w w.j a v a2 s . co m*/ InetSocketAddress adr = (InetSocketAddress) proxy.address(); clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort())); } if (timeout != null) { configBuilder.setConnectTimeout(timeout.intValue()); } if (readTimeout != null) { configBuilder.setSocketTimeout(readTimeout.intValue()); } if (followRedirects != null) { configBuilder.setRedirectsEnabled(followRedirects.booleanValue()); } if (hostnameverifier != null) { SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(), hostnameverifier); clientBuilder.setSSLSocketFactory(sslConnectionFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionFactory) .register("http", PlainConnectionSocketFactory.INSTANCE).build(); clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } clientBuilder.setDefaultRequestConfig(configBuilder.build()); client = clientBuilder.build(); } return client; }
From source file:com.aliyun.api.gateway.demo.Client.java
/** * <br>// ww w . ja v a2s. co m * Client?httpsURL?keystore?storePasswordkeystore??? * <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html">keytool</a> * * @param appKey * APP Key?APIAPP? * @param appSecret * APP?APIAPP? * @param testEnv * ?truefalse */ public Client(String appKey, String appSecret, boolean testEnv) { HttpClientBuilder builder = HttpClients.custom(); try { SSLContext sslContext = null; if (testEnv) { sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { //truetrue return true; } }).build(); } else { //keytool?keystorekeystore KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); sslContext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build(); } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); builder.setSSLSocketFactory(sslsf); } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException | CertificateException | IOException e) { log.error(e.getMessage(), e); } httpClient = builder.setUserAgent(Constants.USER_AGENT).build(); this.appKey = appKey; this.appSecret = appSecret; this.testEnv = testEnv; }
From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java
/** * Returns the HttpClient through which the REST call is made. Uses an * unsafe TrustStrategy in case the user specified a HTTPS URL and * set the ignoreUnverifiedSSLPeer flag. * * @param logger the logger to log messages to * @param build/*from w w w.jav a 2 s .c om*/ * @return the HttpClient */ private HttpClient getHttpClient(PrintStream logger, AbstractBuild<?, ?> build) throws Exception { boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer; String bitbucketServer = bitbucketServerBaseUrl; DescriptorImpl descriptor = getDescriptor(); // Determine if we are using the local or global settings String credentialsId = getCredentialsId(); if (StringUtils.isBlank(credentialsId)) { credentialsId = descriptor.getCredentialsId(); } Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider .lookupCredentials(CertificateCredentials.class, Jenkins.getInstance(), ACL.SYSTEM), CredentialsMatchers.withId(credentialsId)); if ("".equals(bitbucketServer) || bitbucketServer == null) { bitbucketServer = descriptor.getBitbucketRootUrl(); } if (!ignoreUnverifiedSSL) { ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl(); } URL url = new URL(bitbucketServer); HttpClientBuilder builder = HttpClientBuilder.create(); if (url.getProtocol().equals("https") && (ignoreUnverifiedSSL || credentials instanceof CertificateCredentials)) { // add unsafe trust manager to avoid thrown // SSLPeerUnverifiedException try { SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory( buildSslContext(ignoreUnverifiedSSL, credentials), ignoreUnverifiedSSL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : null); builder.setSSLSocketFactory(sslConnSocketFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnSocketFactory).build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(ccm); } catch (NoSuchAlgorithmException nsae) { logger.println("Couldn't establish SSL context:"); nsae.printStackTrace(logger); } catch (KeyManagementException kme) { logger.println("Couldn't initialize SSL context:"); kme.printStackTrace(logger); } catch (KeyStoreException kse) { logger.println("Couldn't initialize SSL context:"); kse.printStackTrace(logger); } } // Configure the proxy, if needed // Using the Jenkins methods handles the noProxyHost settings ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; if (proxyConfig != null) { Proxy proxy = proxyConfig.createProxy(url.getHost()); if (proxy != null && proxy.type() == Proxy.Type.HTTP) { SocketAddress addr = proxy.address(); if (addr != null && addr instanceof InetSocketAddress) { InetSocketAddress proxyAddr = (InetSocketAddress) addr; HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort()); builder = builder.setProxy(proxyHost); String proxyUser = proxyConfig.getUserName(); if (proxyUser != null) { String proxyPass = proxyConfig.getPassword(); BasicCredentialsProvider cred = new BasicCredentialsProvider(); cred.setCredentials(new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass)); builder = builder.setDefaultCredentialsProvider(cred) .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } } } } return builder.build(); }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointAuthority.java
protected void getSharePointSession() throws ManifoldCFException { if (proxy == null) { // Set up server URL try {/* w w w. j a va 2 s . c om*/ if (serverPortString == null || serverPortString.length() == 0) { if (serverProtocol.equals("https")) this.serverPort = 443; else this.serverPort = 80; } else this.serverPort = Integer.parseInt(serverPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(), e); } int proxyPort = 8080; if (proxyPortString != null && proxyPortString.length() > 0) { try { proxyPort = Integer.parseInt(proxyPortString); } catch (NumberFormatException e) { throw new ManifoldCFException(e.getMessage(), e); } } serverUrl = serverProtocol + "://" + serverName; if (serverProtocol.equals("https")) { if (serverPort != 443) serverUrl += ":" + Integer.toString(serverPort); } else { if (serverPort != 80) serverUrl += ":" + Integer.toString(serverPort); } fileBaseUrl = serverUrl + encodedServerLocation; int connectionTimeout = 60000; int socketTimeout = 900000; // Set up ssl if indicated connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); SSLConnectionSocketFactory myFactory = null; if (keystoreData != null) { keystoreManager = KeystoreManagerFactory.make("", keystoreData); myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(), new BrowserCompatHostnameVerifier()); } if (strippedUserName != null) { credentialsProvider.setCredentials(new AuthScope(serverName, serverPort), new NTCredentials(strippedUserName, password, currentHost, ntlmDomain)); } RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout); // If there's a proxy, set that too. if (proxyHost != null && proxyHost.length() > 0) { // Configure proxy authentication if (proxyUsername != null && proxyUsername.length() > 0) { if (proxyPassword == null) proxyPassword = ""; if (proxyDomain == null) proxyDomain = ""; credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain)); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); requestBuilder.setProxy(proxy); } HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager) .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(credentialsProvider); if (myFactory != null) builder.setSSLSocketFactory(myFactory); builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()); httpClient = builder.build(); proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, serverUserName, password, org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd", httpClient, isClaimSpace); } sharepointSessionTimeout = System.currentTimeMillis() + SharePointExpirationInterval; }