@PostConstruct public void afterPropertiesSet() throws Exception { RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create(); schemeRegistry.register("http", PlainConnectionSocketFactory.getSocketFactory()); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(new KeyManager[0], new TrustManager[]{new SimpleTrustManager()}, null); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext); schemeRegistry.register("https", sf); pool = new PoolingHttpClientConnectionManager(schemeRegistry.build()); pool.setMaxTotal(maxConnection); pool.setDefaultMaxPerRoute(maxConnection); pool.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(sotimeout).build()); }
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")); }
private static SSLConnectionSocketFactory createSSLConnectionSocketFactory(Path path, char[] password, boolean strict, KeystoreType keystoreType) { try { SSLContextBuilder builder = SSLContexts.custom(); if (path != null) { KeyStore trustStore = KeyStore.getInstance(keystoreType.name()); try (InputStream is = Files.newInputStream(path)) { trustStore.load(is, password); } builder.loadTrustMaterial(trustStore); } else { builder.loadTrustMaterial(null, new TrustEverythingStrategy()); } X509HostnameVerifier verifier; if (strict) { verifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; } else { verifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; } return new SSLConnectionSocketFactory(builder.build(), new String[] {"TLSv1", "TLSv1.2"}, null, verifier); } catch (IOException | GeneralSecurityException ex) { throw new RuntimeException("Can't create SSL connection factory", ex); } }
@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 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; }
private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException { try { KeyStore keyStore = KeyStoreUtils.createDockerKeyStore(certPath); SSLContext sslContext = SSLContexts.custom() .useTLS() .loadKeyMaterial(keyStore, "docker".toCharArray()) .loadTrustMaterial(keyStore) .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); return RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build(); } catch (GeneralSecurityException e) { throw new IOException(e); } }
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); } }
/** * Sets a Safecharge's default {@link LayeredConnectionSocketFactory} object to set connection properties, * such as supported SSL Protocols, hostname verifier, etc(needed to create a https connection). * * @return this object */ public SafechargeClientBuilder setDefaultSSLSocketFactory() { SSLContext sslContext = SSLContexts.createDefault(); String[] javaSupportedProtocols = sslContext.getSupportedSSLParameters() .getProtocols(); List<String> supportedProtocols = new ArrayList<>(); for (String SERVER_SUPPORTED_SSL_PROTOCOL : SERVER_SUPPORTED_SSL_PROTOCOLS) { for (String javaSupportedProtocol : javaSupportedProtocols) { if (SERVER_SUPPORTED_SSL_PROTOCOL.equals(javaSupportedProtocol)) { supportedProtocols.add(SERVER_SUPPORTED_SSL_PROTOCOL); } } } if (!supportedProtocols.isEmpty()) { sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols.toArray(new String[]{}), null, new DefaultHostnameVerifier()); } else { throw new UnsupportedOperationException("Your Java version doesn't support any of the server supported SSL protocols: " + Arrays.toString( SERVER_SUPPORTED_SSL_PROTOCOLS)); } return this; }
private static HttpClient createAllTrustingClient() throws RestClientException { HttpClient httpclient = null; try { final SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial((TrustStrategy) (X509Certificate[] chain, String authType) -> true); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); httpclient = HttpClients .custom() .setSSLSocketFactory(sslsf) .setMaxConnTotal(1000) .setMaxConnPerRoute(1000) .build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new RestClientException("Cannot create all SSL certificates trusting client", e); } return httpclient; }
public HttpFederationClient(HomeserverState global, FederationDomainResolver resolver) { this.global = global; this.resolver = resolver; try { SocketConfig sockConf = SocketConfig.custom().setSoTimeout(30000).build(); // FIXME properly handle SSL context by validating certificate hostname SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustAllStrategy()).build(); HostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); this.client = HttpClientBuilder.create() .disableAuthCaching() .disableAutomaticRetries() .disableCookieManagement() .disableRedirectHandling() .setDefaultSocketConfig(sockConf) .setSSLSocketFactory(sslSocketFactory) .setUserAgent(global.getAppName() + "/" + global.getAppVersion()) .build(); } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException(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; }
public static String httpsGet(String getUrl, String defaultCharset, Map<String, String> headerParas) throws KeyManagementException, NoSuchAlgorithmException { // 采用绕过验证的方式处理https请求 SSLContext sslcontext = createIgnoreVerifySSL(); // 设置协议http和https对应的处理socket链接工厂的对象 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager); // 创建自定义的httpclient对象 CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).build(); return getInner(getUrl, defaultCharset, headerParas, httpclient); }
private void initPoolingHttpClientManager () { final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", SSLConnectionSocketFactory.getSocketFactory()) .register("http", PlainConnectionSocketFactory.getSocketFactory()).build(); final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(MAX_CONNECTION); connectionManager.setDefaultMaxPerRoute(MAX_CONNECTION_PER_ROUTE); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT) .setConnectionRequestTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT); final RequestConfig requestConfig = requestConfigBuilder.build(); HashSet<Header> defaultHeaders = new HashSet<Header>(); defaultHeaders.add(new BasicHeader(HttpHeaders.PRAGMA, "no-cache")); defaultHeaders.add(new BasicHeader(HttpHeaders.CACHE_CONTROL, "no-cache")); final HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(defaultHeaders).disableAuthCaching().disableContentCompression(); this.httpClient = httpClientBuilder.setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build(); }
/** * Creates the security rest template. * * @throws KeyManagementException the key management exception * @throws NoSuchAlgorithmException the no such algorithm exception * @throws KeyStoreException the key store exception */ private void createSecurityRestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException{ TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); HttpClient httpClient = HttpClientBuilder.create() .disableCookieManagement() .useSystemProperties() .setSSLSocketFactory(csf) .build(); requestFactory.setHttpClient(httpClient); this.restTemplate = new RestTemplate(requestFactory); }
/** * 获取LayeredConnectionSocketFactory 使用ssl单向认证 * * @date 2015年7月17日 * @return */ private LayeredConnectionSocketFactory getSSLSocketFactory() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sslsf; } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
/** * custom http client for server with SSL errors * * @return */ public final CloseableHttpClient getCustomClient() { try { HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties(); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build(); builder.setSSLContext(sslContext); HostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); builder.setConnectionManager(connMgr); return builder.build(); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return getSystemClient(); }
/** * Creates the {@code HostnameVerifier} given the provided {@code verification}. * * @param verification The intended hostname verification action. * @return A verifier for the request verification. * @throws IllegalArgumentException if the provided verification cannot be handled. */ HostnameVerifier getHostnameVerifier(HostnameVerification verification) { // Normally, the configuration logic would give us a default of STRICT if it was not // provided by the user. It's easy for us to do a double-check. if (verification == null) { verification = HostnameVerification.STRICT; } switch (verification) { case STRICT: return SSLConnectionSocketFactory.getDefaultHostnameVerifier(); case NONE: return NoopHostnameVerifier.INSTANCE; default: throw new IllegalArgumentException("Unhandled HostnameVerification: " + hostnameVerification); } }
private static String execute1(HttpUriRequest httpUriRequest) throws Exception { CloseableHttpResponse closeableHttpResponse = null; httpUriRequest.addHeader("Connection", "close"); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().disableCookieManagement().disableConnectionState(); try { httpClientBuilder.setSSLSocketFactory(SSLConnectionSocketFactory.getSocketFactory()); } catch (Exception var12) { LOGGER.error(httpUriRequest.toString(), var12); } CloseableHttpClient httpClient = httpClientBuilder.build(); String var6; try { closeableHttpResponse = httpClient.execute(httpUriRequest); String response = EntityUtils.toString(closeableHttpResponse.getEntity(), CHARSET); var6 = response; } catch (Exception var10) { throw var10; } finally { CloseUtils.close(closeableHttpResponse); CloseUtils.close(httpClient); } return var6; }
@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(); }
private HttpClient httpClient(JiraConnectionProperties jiraConnectionProperties) { try { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial( jiraConnectionProperties.getSslTrustStore().getFile(), jiraConnectionProperties.getSslTrustStorePassword()) .build(); HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(socketFactory, hostnameVerifier); if (jiraConnectionProperties.getSshJumpHost() != null) { sshProxy = new SshProxy(); sslSocketFactory = new SshTunnelSslSocketFactory(sshProxy, sslSocketFactory, jiraConnectionProperties.getSshJumpHost()); } return HttpClientBuilder.create() .setSSLSocketFactory(sslSocketFactory) .build(); } catch (GeneralSecurityException | IOException e) { throw new JiraSyncException("Failed to build custom http client", e); } }
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(); } }
public NestSession(String username, String password) throws LoginException { super(); theLine = null; theBody = null; response = null; theUsername = new String(username); thePassword = new String(password); log.info("Starting Nest login..."); retry = 0; // Trust own CA and all self-signed certs sslcontext = SSLContexts.createDefault(); // Allow TLSv1 protocol only sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) .build(); _login(); }
private CloseableHttpClient createSSLClientDefault() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (cert != null) { for (X509Certificate chainCert : chain) { if (chainCert.equals(cert)) { return true; } } return false; } return true; } }).build(); SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom().setSSLSocketFactory(factory).build(); } catch (GeneralSecurityException e) { logger.error(String.format("SSL connection create Fail : %s", e.getMessage())); } return HttpClients.createDefault(); }
private SSLConnectionSocketFactory buildSSLConnectionSocketFactory() { try { SSLContext sslcontext = SSLContexts.custom() //忽略掉对服务器端证书的校验 .loadTrustMaterial(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); return new SSLConnectionSocketFactory( sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { this.log.error(e.getMessage(), e); } return null; }
@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"); }
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; }
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; }
@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 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"); }
@NotNull private HttpClient getClient(@NotNull SVNURL repositoryUrl) { // TODO: Implement algorithm of resolving necessary enabled protocols (TLSv1 vs SSLv3) instead of just using values from Settings. SSLContext sslContext = createSslContext(repositoryUrl); List<String> supportedProtocols = getSupportedSslProtocols(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, ArrayUtil.toStringArray(supportedProtocols), null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // TODO: Seems more suitable here to read timeout values directly from config file - without utilizing SvnAuthenticationManager. final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (haveDataForTmpConfig()) { IdeHttpClientHelpers.ApacheHttpClient4.setProxyIfEnabled(requestConfigBuilder); IdeHttpClientHelpers.ApacheHttpClient4.setProxyCredentialsIfEnabled(credentialsProvider); } return HttpClients.custom() .setSSLSocketFactory(socketFactory) .setDefaultSocketConfig(SocketConfig.custom() .setSoTimeout(getAuthenticationManager().getReadTimeout(repositoryUrl)) .build()) .setDefaultRequestConfig(requestConfigBuilder .setConnectTimeout(getAuthenticationManager().getConnectTimeout(repositoryUrl)) .build()) .setDefaultCredentialsProvider(credentialsProvider) .build(); }
public static CloseableHttpClient ceateSSLClient(File keyFile, String protocol, String password){ CloseableHttpClient httpclient = null; try{ KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(keyFile); try { keyStore.load(instream, password.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build(); // Allow TLSv1 protocol only String[] protocols = new String[] {protocol}; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,protocols,null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); }catch(Exception e){ e.printStackTrace(); } return httpclient; }
@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"); }