public String notifyHunter(byte[] content) throws IOException { try { String request = new String(content); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build(); HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection"); String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}"; StringEntity entity = new StringEntity(json); entity.setContentType("applicaiton/json"); httpPost.setEntity(entity); HttpResponse response = httpclient.execute(httpPost); String responseString = new BasicResponseHandler().handleResponse(response); return responseString; } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex); } return "Error Notifying Probe Server!"; }
private String getChecksum(String defaultValue, String url, String version) { String result = defaultValue; if (result == null && StringUtils.hasText(url)) { CloseableHttpClient httpClient = HttpClients.custom() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); url = constructUrl(url, version); try { ResponseEntity<String> response = new RestTemplate(requestFactory).exchange( url, HttpMethod.GET, null, String.class); if (response.getStatusCode().equals(HttpStatus.OK)) { result = response.getBody(); } } catch (HttpClientErrorException httpException) { // no action necessary set result to undefined logger.debug("Didn't retrieve checksum because", httpException); } } return result; }
@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); }
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); } }
protected DefaultAbsSender(DefaultBotOptions options) { super(); this.exe = Executors.newFixedThreadPool(options.getMaxThreads()); this.options = options; httpclient = HttpClientBuilder.create() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setConnectionTimeToLive(70, TimeUnit.SECONDS) .setMaxConnTotal(100) .build(); requestConfig = options.getRequestConfig(); if (requestConfig == null) { requestConfig = RequestConfig.copy(RequestConfig.custom().build()) .setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(SOCKET_TIMEOUT) .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); } }
@Override public synchronized void start() { httpclient = HttpClientBuilder.create() .setSSLHostnameVerifier(new NoopHostnameVerifier()) .setConnectionTimeToLive(70, TimeUnit.SECONDS) .setMaxConnTotal(100) .build(); requestConfig = options.getRequestConfig(); exponentialBackOff = options.getExponentialBackOff(); if (exponentialBackOff == null) { exponentialBackOff = new ExponentialBackOff(); } if (requestConfig == null) { requestConfig = RequestConfig.copy(RequestConfig.custom().build()) .setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(SOCKET_TIMEOUT) .setConnectionRequestTimeout(SOCKET_TIMEOUT).build(); } super.start(); }
/** * 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); } }
@Test public void testHostnameVerification() throws Exception { AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class); // Call the real method when(client.getHostnameVerifier(nullable(HostnameVerification.class))) .thenCallRealMethod(); // No verification should give the default (strict) verifier HostnameVerifier actualVerifier = client.getHostnameVerifier(null); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof DefaultHostnameVerifier); actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof DefaultHostnameVerifier); actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof NoopHostnameVerifier); }
private Serializable sendApiMethod(BotApiMethod method) throws TelegramApiException { String responseContent; try { CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); String url = getBaseUrl() + method.getPath(); HttpPost httppost = new HttpPost(url); httppost.addHeader("charset", StandardCharsets.UTF_8.name()); httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = httpclient.execute(httppost); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); } catch (IOException e) { throw new TelegramApiException("Unable to execute " + method.getPath() + " method", e); } JSONObject jsonObject = new JSONObject(responseContent); if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { throw new TelegramApiException("Error at " + method.getPath(), jsonObject.getString("description")); } return method.deserializeResponse(jsonObject); }
CloseableHttpClient configureHttpClient(boolean enableSslVerify) { HttpClientBuilder builder = HttpClientBuilder.create(); if (enableSslVerify) { return builder.build(); } SSLContext sslContext = null; try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { LOG.error("Could not create ssl context", e); } builder.setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLContext(sslContext); return builder.build(); }
private CloseableHttpClient getHttpsClient() { try { RequestConfig config = RequestConfig.custom().setSocketTimeout( 5000 ).setConnectTimeout( 5000 ).build(); SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial( null, ( TrustStrategy ) ( x509Certificates, s ) -> true ); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE ); return HttpClients.custom().setDefaultRequestConfig( config ).setSSLSocketFactory( sslSocketFactory ) .build(); } catch ( Exception e ) { LOGGER.error( e.getMessage() ); } return HttpClients.createDefault(); }
/** * Create the HTTP clean with basic authentication mechanism using specified * credentials * * @param username * Authentication username * @param password * Authentication password * @return */ protected static CloseableHttpClient createHttpClient(String username, String password) { SSLContext sslContext = createSslContext(); HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"); List<Header> headers = Arrays.asList(header); return HttpClients.custom() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLSocketFactory(sslSocketFactory) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultHeaders(headers) .build(); }
/** * Initializes and returns the httpClient with NoopHostnameVerifier * * @return CloseableHttpAsyncClient */ @Override public CloseableHttpAsyncClient getHttpClient() { // Trust own CA and all self-signed certs SSLContext sslcontext = NonValidatingSSLSocketFactory.getSSLContext(); // Allow TLSv1 protocol only SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" }, null, new NoopHostnameVerifier()); List<Header> headers = LogInsightClient.getDefaultHeaders(); asyncHttpClient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).setDefaultHeaders(headers) .build(); asyncHttpClient.start(); return asyncHttpClient; }
/** * Creates {@link HttpClient} that trusts any SSL certificate * * @return prepared HTTP client */ protected HttpClient getSSLAcceptingClient() { final TrustStrategy trustAllStrategy = (final X509Certificate[] chain, final String authType) -> true; try { final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustAllStrategy).build(); sslContext.init(null, getTrustManager(), new SecureRandom()); final SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); return HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException error) { ConsoleUtils.printError(error.getMessage()); throw new IllegalStateException(ErrorMessage.CANNOT_CREATE_SSL_SOCKET, error); } }
/** * Allow SSL connections to utilize untrusted certificates * * @param httpClientBuilder * @throws MojoExecutionException */ private void configureInsecureSSL(HttpClientBuilder httpClientBuilder) throws MojoExecutionException { try { SSLContextBuilder sslBuilder = new SSLContextBuilder(); // Accept all Certificates sslBuilder.loadTrustMaterial(null, AcceptAllTrustStrategy.INSTANCE); SSLContext sslContext = sslBuilder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); httpClientBuilder.setSSLSocketFactory(sslsf); } catch (Exception e) { throw new MojoExecutionException("Error setting insecure SSL configuration", e); } }
public VaultAdminClient getClient(final String vaultRootToken, final String hostname) { final ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) .build(); final OkHttpClient httpClient = new OkHttpClient.Builder() .hostnameVerifier(new NoopHostnameVerifier()) .connectionSpecs(Lists.newArrayList(spec)) .proxy(proxy) .connectTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) .writeTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) .readTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) .build(); return new VaultAdminClient( new StaticVaultUrlResolver(toVaultUrl(hostname)), new RootCredentialsProvider(vaultRootToken), httpClient); }
@Test public void run_restore_complete() throws IOException { when(consoleService.readLine(anyString())).thenReturn("proceed"); CerberusAdminClient adminClient = new CerberusAdminClient( new StaticVaultUrlResolver("http://127.0.0.1:8200"), new VaultAdminClientFactory.RootCredentialsProvider(rootToken), new OkHttpClient.Builder() .hostnameVerifier(new NoopHostnameVerifier()) .connectTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) .writeTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) .readTimeout(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT) .build(), CerberusModule.configObjectMapper() ); when(vaultAdminClientFactory.createCerberusAdminClient(anyString())).thenReturn(adminClient); operation.run(command); }
public static void revokeOAuthToken(final String refreshToken, final OAuthProvider prov) throws IOException{ final String uriStr; switch (prov) { case Google: uriStr = "https://accounts.google.com/o/oauth2/revoke?token="; break; default: throw new IOException("Unknown OAuth Provider: " + prov); } CloseableHttpClient client = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); HttpGet get = new HttpGet(uriStr + refreshToken); HttpResponse response = client.execute(get); final int status = response.getStatusLine().getStatusCode(); if (status != 200) { String reason = response.getStatusLine().getReasonPhrase(); logger.error(reason); throw new ClientErrorException(reason, status); } }
/** * 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); }
public static HttpClient buildHttpClient(boolean sslEnable, boolean allowSelfSigendCerts, OAuthSigner signer, String host, int port, int socketTimeoutInMillis) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { List<HttpClientConfiguration> configs = new ArrayList<>(); HttpClientConfig httpClientConfig = HttpClientConfig.newBuilder().setSocketTimeoutInMillis(socketTimeoutInMillis).build(); configs.add(httpClientConfig); if (sslEnable) { HttpClientSSLConfig.Builder builder = HttpClientSSLConfig.newBuilder(); builder.setUseSSL(true); if (allowSelfSigendCerts) { SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only, use NoopHostnameVerifier to trust self-singed cert builder.setUseSslWithCustomSSLSocketFactory(new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, new NoopHostnameVerifier())); } configs.add(builder.build()); } HttpClientFactory httpClientFactory = new HttpClientFactoryProvider().createHttpClientFactory(configs, false); return httpClientFactory.createClient(signer, host, port); }
private RestTemplate getRestTemplateAllowingSelfSigned() { try { final SSLContext allowSelfSignedSslContext = SSLContexts .custom() .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( allowSelfSignedSslContext, NoopHostnameVerifier.INSTANCE ); final CloseableHttpClient httpClient = HttpClientBuilder .create() .setSSLSocketFactory(sslsf) .build(); return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); } catch (final Exception exception) { throw new SQCompanionException("Can't initialize RestTemplate with Self Signed https support", exception); } }
protected HttpClient getHttpClient(Map<String, Object> options) throws GeneralSecurityException { SocketConfig socketConfig = SocketConfig.custom() .setSoKeepAlive(true).build(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultSocketConfig(socketConfig); httpClientBuilder.disableAuthCaching(); httpClientBuilder.disableAutomaticRetries(); if(options.containsKey("sslVerify") && !Boolean.parseBoolean(options.get("sslVerify").toString())) { log.debug("Disabling all SSL certificate verification."); SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }); httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier()); httpClientBuilder.setSSLContext(sslContextBuilder.build()); } return httpClientBuilder.build(); }
private String getFileAndroid(String query) { String result = null; try { CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); HttpGet request = new HttpGet(BASEURLAndroid.replace("@language", query)); HttpResponse response = client.execute(request); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String line; String responseString = ""; while ((line = rd.readLine()) != null) { responseString += line; } if (response.getStatusLine().getStatusCode() == STATUS200) { result = responseString; } } catch (IOException e) { BotLogger.error(LOGTAG, e); } return result; }
private void setupSSLclient() { // Handle SSL SSLContext sslcontext = null; SSLConnectionSocketFactory factory = null; try { sslcontext = SSLContexts.custom().useProtocol("SSL").build(); sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom()); factory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier()); } catch (KeyManagementException | NoSuchAlgorithmException e) { // TODO Auto-generated catch block logError("Could not create SSL context. Entering fail state."); throw new Error(e.getMessage()); } // Create client and context for web stuff. httpclient = HttpClientBuilder.create().setSSLSocketFactory(factory).build(); }
@Test public void testGetHostnameVerifier() { // Default HostnameVerifier verifier = SSLUtils.getHostnameVerifier(config); assertTrue(verifier instanceof DefaultHostnameVerifier); // Override config.setOverrideHostnameVerifier(new TestHostnameVerifier()); verifier = SSLUtils.getHostnameVerifier(config); assertTrue(verifier instanceof TestHostnameVerifier); // Disabled config.setDisableSSLValidation(true); verifier = SSLUtils.getHostnameVerifier(config); assertTrue(verifier instanceof NoopHostnameVerifier); }
public CloseableHttpClient getAuthenticatedClient() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build(), NoopHostnameVerifier.INSTANCE); return HttpClients.custom() .setSSLSocketFactory(sslsf) .setDefaultCredentialsProvider(getCredentialsProvider()) .build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex); return null; } }
@Scheduled(cron = "0 0 5,18 * * ?") public void run() { for (Account account : getAccounts()) { try { CloseableHttpClient client = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); Executor executor = Executor.newInstance(client).use(new BasicCookieStore()); String token = login(executor, account); if(StringUtils.isNotEmpty(token)) { if(checkIn(executor, account, token)) { // lottery(executor, account, token); } } } catch (Exception e) { log.error("【SMZDM】【" + account.getUsername() + "】签到异常", e); } } }
private static CloseableHttpClient createInsecureSslHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { final SSLContext sslContext = new SSLContextBuilder() .useProtocol(INSECURE_SSL_PROTOCOL) .loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf) .build(); final HttpClientConnectionManager connectionManager = createConnectionManager(socketFactoryRegistry); return HttpClients.custom() .setConnectionManager(connectionManager) .setSSLSocketFactory( sslsf).build(); }
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) { SSLContext sslContext = org.apache.http.ssl.SSLContexts.createDefault(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory) .build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST), new UsernamePasswordCredentials(username, password)); return HttpClientBuilder.create() .setConnectionManager(new PoolingHttpClientConnectionManager(registry)) .setRetryHandler(new StandardHttpRequestRetryHandler(5, true)) .setDefaultCredentialsProvider(credentialsProvider) .build(); }
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) { try { SSLContext sslContext = SSLContexts.createDefault(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionSocketFactory) .register("http", PlainConnectionSocketFactory.getSocketFactory()) .build(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST), new UsernamePasswordCredentials(username, password)); PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry); HttpClientBuilder.create().setConnectionManager(connectionPool).build(); return HttpClientBuilder.create() .setConnectionManager(connectionPool) .setRetryHandler(new StandardHttpRequestRetryHandler(5, true)) .setDefaultCredentialsProvider(credsProvider).build(); } catch (Exception e) { throw new RuntimeException(e); } }
@Bean public CloseableHttpClient httpClient() { try { //new ClassPathResource("").getURL() SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(keyStore, keyPassword.toCharArray(), new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslcontext, NoopHostnameVerifier.INSTANCE); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .build(); } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new BeanCreationException("Failed to create http client for ssl connection", e); } }
/** * Returns a client with all our selected properties / params and SSL enabled. * * @return client */ public static final HttpClient getSecureClient() { HttpClientBuilder client = HttpClientBuilder.create(); // set the ssl verifier to accept all client.setSSLHostnameVerifier(new NoopHostnameVerifier()); // set the connection manager client.setConnectionManager(connectionManager); // dont retry client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); // establish a connection within x seconds RequestConfig config = RequestConfig.custom().setSocketTimeout(connectionTimeout).build(); client.setDefaultRequestConfig(config); // no redirects client.disableRedirectHandling(); // set custom ua client.setUserAgent(userAgent); return client.build(); }
public AutoOnboardPinotMetricsUtils(DataSourceConfig dataSourceConfig) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { PinotThirdEyeDataSourceConfig pinotThirdeyeDataSourceConfig = PinotThirdEyeDataSourceConfig.createFromDataSourceConfig(dataSourceConfig); String controllerConnectionScheme = pinotThirdeyeDataSourceConfig.getControllerConnectionScheme(); if (PinotThirdEyeDataSourceConfig.HTTPS_SCHEME.equals(controllerConnectionScheme)) { try { // Accept all SSL certificate because we assume that the Pinot broker are setup in the same internal network SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new AcceptAllTrustStrategy()).build(); this.pinotControllerClient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // This section shouldn't happen because we use Accept All Strategy LOG.error("Failed to start auto onboard for Pinot data source."); throw e; } } else { this.pinotControllerClient = HttpClients.createDefault(); } this.pinotControllerHost = new HttpHost(pinotThirdeyeDataSourceConfig.getControllerHost(), pinotThirdeyeDataSourceConfig.getControllerPort(), controllerConnectionScheme); }
private Executor executor() { if (executor == null) { if (this.host.startsWith("https://")) { try { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, (chain, authType) -> true) .build(); builder.setSSLContext(sslContext); builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); } catch (Exception ex) { Throwables.propagate(ex); } } client = builder.build(); executor = Executor.newInstance(client); if (creds != null) { executor.auth(creds); } } return executor; }
public static CloseableHttpClient newClient(int timeout) { HttpClientBuilder builder = HttpClients.custom(); builder.useSystemProperties(); builder.addInterceptorFirst(REMOVE_INCORRECT_CONTENT_ENCODING); builder.disableAutomaticRetries(); builder.setSSLContext(SSL_CONTEXT); builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); RequestConfig.Builder configBuilder = RequestConfig.custom(); configBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); configBuilder.setSocketTimeout(timeout); configBuilder.setConnectTimeout(timeout); configBuilder.setConnectionRequestTimeout(timeout); builder.setDefaultRequestConfig(configBuilder.build()); builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.ISO_8859_1).build()); return builder.build(); }
/** * Sets the client's {@link javax.net.ssl.SSLContext} to use * {@link HttpUtils#buildCertificateIgnoringSslContext()}. * * @return a reference to {@code this} to enable chained method invocation */ public HttpClientConfigurer skipTlsCertificateVerification() { httpClientBuilder.setSSLContext(HttpUtils.buildCertificateIgnoringSslContext()); httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier()); return this; }