Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#setSSLHostnameVerifier()

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#setSSLHostnameVerifier() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ODataUtil.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link HttpClientBuilder} for the given options.
 *
 * @return the new http client builder
 */
public static HttpClientBuilder createHttpClientBuilder(Map<String, Object> options) {
    HttpClientBuilder builder = HttpClientBuilder.create();

    SSLContext sslContext = createSSLContext(options);
    if (sslContext != null) {
        // Skip verifying hostname
        HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
        builder.setSSLContext(sslContext);
        builder.setSSLHostnameVerifier(allowAllHosts);
    }

    CredentialsProvider credentialsProvider = createCredentialProvider(options);
    if (credentialsProvider != null) {
        builder.setDefaultCredentialsProvider(credentialsProvider).build();
    }

    return builder;
}
 
Example 2
Source File: HttpWorkflowStepPlugin.java    From rundeck-http-plugin with ISC License 6 votes vote down vote up
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();
}
 
Example 3
Source File: HttpConnectionUtil.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 4
Source File: HttpGetter.java    From commafeed with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 5
Source File: SSLNoVerifyCertificateManagerClientBuilderExtension.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public HttpClientBuilder extend(HttpClientBuilder httpClientBuilder, GerritAuthData authData) {
  HttpClientBuilder builder = super.extend(httpClientBuilder, authData);
  builder.setSSLContext(trustAnyX509Certificate);
  builder.setSSLHostnameVerifier(acceptAnyX509Hostname);
  return builder;
}
 
Example 6
Source File: HttpClient.java    From qonduit with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

    HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(defaultRequestConfig);
    if (hostVerificationEnabled) {
        builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
    } else {
        builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }
    return builder.build();
}
 
Example 7
Source File: HttpClientUtils.java    From spring-cloud-dashboard with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates.
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(
		RestTemplate restTemplate,
		String username,
		String password,
		boolean skipSslValidation) {

	Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

	final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

	if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
		final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY,
				new UsernamePasswordCredentials(
						username,
						password));
		httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
	}

	if (skipSslValidation) {
		httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
		httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
	}

	final CloseableHttpClient httpClient = httpClientBuilder.build();
	final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
	restTemplate.setRequestFactory(requestFactory);
}
 
Example 8
Source File: Main.java    From git-lfs-migrate with MIT License 5 votes vote down vote up
@NotNull
private static Client createClient(@NotNull AuthProvider auth, @NotNull CmdArgs cmd) throws GeneralSecurityException {
  final HttpClientBuilder httpBuilder = HttpClients.custom();
  httpBuilder.setUserAgent("git-lfs-migrate");
  if (cmd.noCheckCertificate) {
    httpBuilder.setSSLHostnameVerifier((hostname, session) -> true);
    httpBuilder.setSSLContext(SSLContexts.custom()
        .loadTrustMaterial((chain, authType) -> true)
        .build());
  }
  return new Client(auth, httpBuilder.build());
}
 
Example 9
Source File: HttpClientSupport.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
public static HttpClientBuilder builder(
		HttpEnvironmentRepositoryProperties environmentProperties)
		throws GeneralSecurityException {
	SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
	HttpClientBuilder httpClientBuilder = HttpClients.custom();

	if (environmentProperties.isSkipSslValidation()) {
		sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true);
		httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
	}

	if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) {
		ProxyHostProperties httpsProxy = environmentProperties.getProxy()
				.get(ProxyHostProperties.ProxyForScheme.HTTPS);
		ProxyHostProperties httpProxy = environmentProperties.getProxy()
				.get(ProxyHostProperties.ProxyForScheme.HTTP);

		httpClientBuilder
				.setRoutePlanner(new SchemeBasedRoutePlanner(httpsProxy, httpProxy));
		httpClientBuilder.setDefaultCredentialsProvider(
				new ProxyHostCredentialsProvider(httpProxy, httpsProxy));
	}
	else {
		httpClientBuilder.setRoutePlanner(
				new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
		httpClientBuilder.setDefaultCredentialsProvider(
				new SystemDefaultCredentialsProvider());
	}

	int timeout = environmentProperties.getTimeout() * 1000;
	return httpClientBuilder.setSSLContext(sslContextBuilder.build())
			.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(timeout)
					.setConnectTimeout(timeout).build());
}
 
Example 10
Source File: ConcurrentLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected CloseableHttpClient getHttpsAwareClient() {
    HttpClientBuilder builder = HttpClientBuilder.create()
          .setRedirectStrategy(new LaxRedirectStrategy());
    if (AUTH_SERVER_SSL_REQUIRED) {
        builder.setSSLHostnameVerifier((s, sslSession) -> true);
    }
    return builder.build();
}
 
Example 11
Source File: HttpClientFactory.java    From vividus with Apache License 2.0 4 votes vote down vote up
@Override
public IHttpClient buildHttpClient(HttpClientConfig config)
{
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultHeaders(config.createHeaders());
    if (config.hasCookieStore())
    {
        builder.setDefaultCookieStore(config.getCookieStore());
    }
    if (config.hasCredentials())
    {
        AuthScope authScope = config.hasAuthScope() ? config.getAuthScope()
                : ClientBuilderUtils.DEFAULT_AUTH_SCOPE;
        CredentialsProvider credProvider = ClientBuilderUtils.createCredentialsProvider(authScope,
                config.getCredentials());
        builder.setDefaultCredentialsProvider(credProvider);
    }

    sslContextFactory.getSslContext(SSLConnectionSocketFactory.SSL, !config.isSslCertificateCheckEnabled())
            .ifPresent(builder::setSSLContext);

    if (!config.isSslHostnameVerificationEnabled())
    {
        builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }
    builder.setConnectionManager(config.getConnectionManager());
    builder.setMaxConnTotal(config.getMaxTotalConnections());
    builder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    builder.addInterceptorLast(config.getLastRequestInterceptor());
    builder.addInterceptorLast(config.getLastResponseInterceptor());
    builder.setRedirectStrategy(config.getRedirectStrategy());
    builder.setRetryHandler(config.getHttpRequestRetryHandler());
    Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(config.getConnectionRequestTimeout());
    requestConfigBuilder.setConnectTimeout(config.getConnectTimeout());
    requestConfigBuilder.setCircularRedirectsAllowed(config.isCircularRedirectsAllowed());
    requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    Optional.ofNullable(config.getCookieSpec()).ifPresent(requestConfigBuilder::setCookieSpec);
    builder.setDefaultRequestConfig(requestConfigBuilder.build());
    builder.setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT)
            .setSoTimeout(config.getSocketTimeout())
            .build());
    builder.setDnsResolver(config.getDnsResolver());

    HttpClient httpClient = new HttpClient();
    httpClient.setCloseableHttpClient(builder.build());
    if (config.hasBaseUrl())
    {
        httpClient.setHttpHost(HttpHost.create(config.getBaseUrl()));
    }
    httpClient.setSkipResponseEntity(config.isSkipResponseEntity());
    return httpClient;
}
 
Example 12
Source File: AbstractHttpTransportFactory.java    From bender with Apache License 2.0 4 votes vote down vote up
protected HttpClientBuilder getClientBuilder(boolean useSSL, String url,
    Map<String, String> stringHeaders, int socketTimeout) {

  HttpClientBuilder cb = HttpClientBuilder.create();

  /*
   * Setup SSL
   */
  if (useSSL) {
    /*
     * All trusting SSL context
     */
    try {
      cb.setSSLContext(getSSLContext());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    /*
     * All trusting hostname verifier
     */
    cb.setSSLHostnameVerifier(new HostnameVerifier() {
      public boolean verify(String s, SSLSession sslSession) {
        return true;
      }
    });
  }

  /*
   * Add default headers
   */
  ArrayList<BasicHeader> headers = new ArrayList<BasicHeader>(stringHeaders.size());
  stringHeaders.forEach((k, v) -> headers.add(new BasicHeader(k, v)));
  cb.setDefaultHeaders(headers);

  /*
   * Set socket timeout and transport threads
   */
  SocketConfig sc = SocketConfig.custom().setSoTimeout(socketTimeout).build();
  cb.setDefaultSocketConfig(sc);
  cb.setMaxConnPerRoute(this.config.getThreads());
  cb.setMaxConnTotal(this.config.getThreads());

  return cb;
}
 
Example 13
Source File: ApacheGatewayConnection.java    From vespa with Apache License 2.0 4 votes vote down vote up
public HttpClient createClient() {
    HttpClientBuilder clientBuilder;
    if (connectionParams.useTlsConfigFromEnvironment()) {
        clientBuilder = VespaHttpClientBuilder.create();
    } else {
        clientBuilder = HttpClientBuilder.create();
        if (connectionParams.getSslContext() != null) {
            setSslContext(clientBuilder, connectionParams.getSslContext());
        } else {
            SslContextBuilder builder = new SslContextBuilder();
            if (connectionParams.getPrivateKey() != null && connectionParams.getCertificate() != null) {
                builder.withKeyStore(connectionParams.getPrivateKey(), connectionParams.getCertificate());
            }
            if (connectionParams.getCaCertificates() != null) {
                builder.withTrustStore(connectionParams.getCaCertificates());
            }
            setSslContext(clientBuilder, builder.build());
        }
        if (connectionParams.getHostnameVerifier() != null) {
            clientBuilder.setSSLHostnameVerifier(connectionParams.getHostnameVerifier());
        }
        clientBuilder.setUserTokenHandler(context -> null); // https://stackoverflow.com/a/42112034/1615280
    }
    clientBuilder.setMaxConnPerRoute(1);
    clientBuilder.setMaxConnTotal(1);
    clientBuilder.setConnectionTimeToLive(connectionParams.getConnectionTimeToLive().getSeconds(), TimeUnit.SECONDS);
    clientBuilder.setUserAgent(String.format("vespa-http-client (%s)", Vtag.currentVersion));
    clientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(Headers.CLIENT_VERSION, Vtag.currentVersion)));
    clientBuilder.disableContentCompression();
    // Try to disable the disabling to see if system tests become stable again.
    // clientBuilder.disableAutomaticRetries();
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setSocketTimeout(0);
    if (connectionParams.getProxyHost() != null) {
        requestConfigBuilder.setProxy(new HttpHost(connectionParams.getProxyHost(), connectionParams.getProxyPort()));
    }
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    log.fine("Creating HttpClient: " + " ConnectionTimeout "
                    + " SocketTimeout 0 secs "
                    + " proxyhost (can be null) " + connectionParams.getProxyHost()
                    + ":" + connectionParams.getProxyPort()
                    + (useSsl ? " using ssl " : " not using ssl")
    );
    return clientBuilder.build();
}