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; }
@Test public void testHome() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); TestRestTemplate testRestTemplate = new TestRestTemplate(); ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertTrue( "Result is not Matched with Server Response",entity.getBody().contains("welcome to the application")); }
@Bean public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(sslConnectionSocketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); return new RestTemplate(requestFactory); }
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, 25555), new UsernamePasswordCredentials(username, password)); SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .useTLS() .build(); SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); HttpClient httpClient = HttpClientBuilder.create() .disableRedirectHandling() .setDefaultCredentialsProvider(credentialsProvider) .setSSLSocketFactory(connectionFactory) .build(); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); restTemplate.getInterceptors().addAll(interceptors); return restTemplate; }
private SSLConnectionSocketFactory getSSLConnectionSocketFactory() { // Trust own CA and all self-signed certificates SSLContext sslcontext = null; try { sslcontext = SSLContexts.custom() .loadTrustMaterial(new File("sepa.jks"), "*sepa.jks*".toCharArray(),new TrustSelfSignedStrategy()) .build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e1) { logger.error(e1.getMessage()); return null; } // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, new SEPAHostnameVerifier()); return sslsf; }
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); } }
public static String triggerHttpGetWithCustomSSL(String requestUrl) { String result = null; try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }); @SuppressWarnings("deprecation") HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), hostnameVerifier); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); HttpGet httpGet = new HttpGet("https://" + requestUrl); CloseableHttpResponse response = httpclient.execute(httpGet); try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); log.debug("Received response: " + result); } else { log.error("Request not successful. StatusCode was " + response.getStatusLine().getStatusCode()); } } finally { response.close(); } } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { log.error("Error executing the request.", e); } return result; }
@Test public void contextLoads() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange("https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute?env=stage&key=PING", HttpMethod.GET, entity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertEquals(new Integer(0), response.getBody().getCode()); Assert.assertNotNull(response.getBody().getOutput()); httpClient.close(); }
@Test public void hello() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN)); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange("https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute/hello", HttpMethod.GET, entity, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Assert.assertNotNull(response.getBody()); httpClient.close(); }
@Test public void executeCommands() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=DEPLOY&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebedx&env=stage", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_Bounce() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=BOUNCE&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebmobile&env=dev", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_Status() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<ExecutionStatus> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute" + "?key=STATUS&groupId=service.registration&name=assurantregistrationservice&version=2.1.6&clusterName=aebedx&env=stage", HttpMethod.POST, requestEntity, ExecutionStatus.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); httpClient.close(); }
@Test public void executeCommands_NoKey() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory) restTemplate.getRestTemplate().getRequestFactory()) .setHttpClient(httpClient); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<HashMap<String, String>> requestEntity = new HttpEntity<>(headers); ResponseEntity<Object> response = restTemplate.exchange( "https://localhost:" + this.port + this.contextRoot + this.jerseycontextRoot + "/execute", HttpMethod.POST, requestEntity, Object.class); Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Assert.assertNotNull(response.getBody()); httpClient.close(); }
public void init() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); Unirest.setHttpClient(httpclient); } catch (Exception e) { System.out.println("Failed to start server: " + e.toString()); e.printStackTrace(); } }
@Test public void testWelcome() throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); TestRestTemplate testRestTemplate = new TestRestTemplate(); ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) .setHttpClient(httpClient); ResponseEntity<String> entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals("welcome to the application "+System.getProperty("user.name"), entity.getBody()); }
@Test public void sslDisabled() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); Ssl ssl = getSsl(null, "password", "classpath:test.jks"); ssl.setEnabled(false); factory.setSsl(ssl); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); this.thrown.expect(SSLException.class); getResponse(getLocalUrl("https", "/hello"), requestFactory); }
@Test public void sslGetScheme() throws Exception { // gh-2232 AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks")); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) .contains("scheme=https"); }
protected final void testBasicSslWithKeyStore(String keyStore) throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(null, "password", keyStore)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test public void pkcs12KeyStoreAndTrustStore() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, null, "classpath:test.p12", "classpath:test.p12", null, null)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(new FileInputStream(new File("src/test/resources/test.p12")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "secret".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", "classpath:test.jks", null, null)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "password".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test(expected = IOException.class) public void sslNeedsClientAuthenticationFailsWithoutClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); getResponse(getLocalUrl("https", "/test.txt"), requestFactory); }
@Test public void sslWantsClientAuthenticationSucceedsWithClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, "password".toCharArray()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
@Test public void sslWantsClientAuthenticationSucceedsWithoutClientCertificate() throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(ClientAuth.WANT, "password", "classpath:test.jks")); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)) .isEqualTo("test"); }
protected void testRestrictedSSLProtocolsAndCipherSuites(String[] protocols, String[] ciphers) throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); factory.setSsl(getSsl(null, "password", "src/test/resources/test.jks", null, protocols, ciphers)); this.container = factory.getEmbeddedServletContainer( new ServletRegistrationBean(new ExampleServlet(true, false), "/hello")); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) .contains("scheme=https"); }
public static void setupHttpsUnirest() { SSLContext sslcontext = null; try { sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { fail(e.toString()); } SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); Unirest.setHttpClient(httpclient); }
HttpPosterThread(LinkedBlockingQueue<String> lbq, String url) throws Exception { this.lbq = lbq; this.url = url; SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); httpClient = HttpClients.custom().setSSLSocketFactory( sslsf).build(); //httpClient = HttpClientBuilder.create().build(); httpPost = new HttpPost(url); cntErr = 0; }
public AbstractRestTemplateClient ignoreAuthenticateServer() { //backward compatible with android httpclient 4.3.x if(restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); X509HostnameVerifier verifier = ignoreSslWarning ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, verifier); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory()).setHttpClient(httpClient); } catch (Exception e) { e.printStackTrace(); } } else { Debug.error("the request factory " + restTemplate.getRequestFactory().getClass().getName() + " does not support ignoreAuthenticateServer"); } return this; }
/** * This method creates an insecure SSL factory that will trust on self signed certificates. * For that we use {@link TrustSelfSignedStrategy}. */ protected SSLConnectionSocketFactory createInsecureSslFactory() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(new TrustSelfSignedStrategy()); SSLContext sc = builder.build(); if (acceptAllKindsOfCertificates) { TrustManager[] trustAllCerts = new TrustManager[1]; TrustManager tm = new TrustAllManager(); trustAllCerts[0] = tm; sc.init(null, trustAllCerts, null); HostnameVerifier hostnameVerifier = createInsecureHostNameVerifier(); return new SSLConnectionSocketFactory(sc, hostnameVerifier); } return new SSLConnectionSocketFactory(sc); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new ApacheCloudStackClientRuntimeException(e); } }
@Test public void testProxyAuthWithSSL() throws Exception { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(new File(keyStoreFile), keystorePW.toCharArray(), new TrustSelfSignedStrategy()) .build(); try (CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext) .setSSLHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }).build()) { Executor ex = Executor.newInstance(httpclient); Response response = ex.execute(Request.Get("https://localhost:9200/blahobar.234324234/logs/1") .addHeader("Authorization", String.format("Bearer %s", token)) .addHeader("X-Proxy-Remote-User", proxyUser)); System.out.println(response.returnContent().asString()); } catch (Exception e) { System.out.println(e); fail("Test Failed"); } }
public void initClientSession() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(TRUSTSTORE_FILE, TRUSTSTORE_PASS.toCharArray(), new TrustSelfSignedStrategy()) .loadKeyMaterial(KEYSTORE_FILE, KEYSTORE_PASS.toCharArray(), KEYSTORE_PASS.toCharArray()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); this.httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf) .build(); }
/** * no-arg constructor for client */ public TankHttpClient4() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE); } catch (Exception e) { LOG.error("Error setting accept all: " + e, e); } httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); requestConfig = RequestConfig.custom().setSocketTimeout(30000) .setConnectTimeout(30000) .setCircularRedirectsAllowed(true) .setAuthenticationEnabled(true) .setRedirectsEnabled(true) .setCookieSpec(CookieSpecs.STANDARD) .setMaxRedirects(100).build(); // Make sure the same context is used to execute logically related // requests context = HttpClientContext.create(); context.setCredentialsProvider(new BasicCredentialsProvider()); context.setCookieStore(new BasicCookieStore()); context.setRequestConfig(requestConfig); }