List of usage examples for org.apache.http.impl.client HttpClientBuilder setSSLSocketFactory
public final HttpClientBuilder setSSLSocketFactory(final LayeredConnectionSocketFactory sslSocketFactory)
From source file:securitytools.common.http.HttpClientFactory.java
public static CloseableHttpClient build(ClientConfiguration clientConfiguration) throws NoSuchAlgorithmException { HttpClientBuilder builder = HttpClients.custom(); // Certificate Validation if (clientConfiguration.isCertificateValidationEnabled()) { builder.setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContext.getDefault(), SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER)); } else {/*from w w w .j a v a 2s. co m*/ // Disable builder.setSSLSocketFactory(new TrustingSSLConnectionSocketFactory()); } // Timeouts RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectTimeout(clientConfiguration.getConnectionTimeout()); requestConfigBuilder.setConnectionRequestTimeout(clientConfiguration.getConnectionTimeout()); requestConfigBuilder.setSocketTimeout(clientConfiguration.getSocketTimeout()); builder.setDefaultRequestConfig(requestConfigBuilder.build()); // User Agent builder.setUserAgent(clientConfiguration.getUserAgent()); // Proxy if (clientConfiguration.getProxyHost() != null) { builder.setProxy(clientConfiguration.getProxyHost()); } return builder.build(); }
From source file:net.officefloor.plugin.socket.server.http.HttpTestUtil.java
/** * Configures the {@link HttpClientBuilder} for HTTPS. * /*www . j av a 2 s . c o m*/ * @param builder * {@link HttpClientBuilder}. * * @see #getSslEngineSourceClass() */ public static void configureHttps(HttpClientBuilder builder) { // Provide SSL Socket Factory builder.setSSLSocketFactory(new OfficeFloorDefaultSocketFactory()); }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {//from w w w . j a va 2 s . c o m CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:com.github.pascalgn.jiracli.web.HttpClient.java
private static CloseableHttpClient createHttpClient() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setSSLSocketFactory(SSL_SOCKET_FACTORY); return httpClientBuilder.build(); }
From source file:org.apache.cxf.fediz.integrationtests.KerberosTest.java
public static String sendHttpGet(String url, String ticket, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {// www . j a va 2 s . c om KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); httpget.addHeader("Authorization", "Negotiate " + ticket); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); System.out.println(response.getStatusLine()); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
/** * Same as sendHttpGet above, except that we return the HttpClient so that it can * subsequently be re-used (for e.g. logout) *///from ww w. j a v a 2 s. com public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); String responseStr = EntityUtils.toString(entity); Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0); return httpClient; }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {//from w w w. ja v a2s.c o m CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { return null; } // Redirect to a POST is not supported without user interaction // http://www.ietf.org/rfc/rfc2616.txt // If the 301 status code is received in response to a request other // than GET or HEAD, the user agent MUST NOT automatically redirect the // request unless it can be confirmed by the user, since this might // change the conditions under which the request was issued. Source source = new Source(EntityUtils.toString(entity)); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); FormFields formFields = source.getFormFields(); List<Element> forms = source.getAllElements(HTMLElementName.FORM); Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size()); String postUrl = forms.get(0).getAttributeValue("action"); Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa")); Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult")); for (FormField formField : formFields) { if (formField.getUserValueCount() != 0) { nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0))); } } HttpPost httppost = new HttpPost(postUrl); httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpClient.execute(httppost); entity = response.getEntity(); System.out.println(response.getStatusLine()); Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.model.CustomJenkinsHttpClient.java
private static HttpClientBuilder createHttpClientBuilder(final boolean verifyCertificate, final CustomProxy customProxy) { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.useSystemProperties(); if (!verifyCertificate) { SSLContextBuilder builder = new SSLContextBuilder(); try {/*www .j ava2s .c o m*/ builder.loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build())); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { LOGGER.severe(ExceptionUtils.getFullStackTrace(e)); } } if (customProxy != null) { Jenkins jenkins = PerfSigUIUtils.getInstance(); if (customProxy.isUseJenkinsProxy() && jenkins.proxy != null) { final ProxyConfiguration proxyConfiguration = jenkins.proxy; if (StringUtils.isNotBlank(proxyConfiguration.name) && proxyConfiguration.port > 0) { httpClientBuilder.setProxy(new HttpHost(proxyConfiguration.name, proxyConfiguration.port)); if (StringUtils.isNotBlank(proxyConfiguration.getUserName())) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials( proxyConfiguration.getUserName(), proxyConfiguration.getUserName()); credsProvider.setCredentials( new AuthScope(proxyConfiguration.name, proxyConfiguration.port), usernamePasswordCredentials); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } } } else { httpClientBuilder.setProxy(new HttpHost(customProxy.getProxyServer(), customProxy.getProxyPort())); if (StringUtils.isNotBlank(customProxy.getProxyUser()) && StringUtils.isNotBlank(customProxy.getProxyPassword())) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials( customProxy.getProxyUser(), customProxy.getProxyPassword()); credsProvider.setCredentials( new AuthScope(customProxy.getProxyServer(), customProxy.getProxyPort()), usernamePasswordCredentials); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } } } return httpClientBuilder; }
From source file:org.jboss.pnc.auth.keycloakutil.util.HttpUtil.java
public static HttpClient getHttpClient() { if (httpClient == null) { HttpClientBuilder clientBuilder = HttpClientBuilder.create().useSystemProperties(); if (sslRequired) { if (sslsf != null) { clientBuilder.setSSLSocketFactory(sslsf); }//from www . j a v a 2 s . com } else { SSLContext sslContext; try { sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }, new SecureRandom()); } catch (NoSuchAlgorithmException ex) { throw new AuthenticationException("Cannot get SSLContext instance for \"SSL\" protocol.", ex); } catch (KeyManagementException ex) { throw new AuthenticationException("SSLContext initialization failed.", ex); } clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext); } httpClient = clientBuilder.build(); } return httpClient; }
From source file:com.threatconnect.app.playbooks.db.tcapi.ConnectionUtil.java
/** * Adds the ability to trust self signed certificates for this HttpClientBuilder * /*w w w. j a v a 2 s.com*/ * @param httpClientBuilder * the HttpClientBuilder to apply these settings to */ public static void trustSelfSignedCerts(final HttpClientBuilder httpClientBuilder) { logger.debug("Trusting self-signed certs."); 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); } }