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

The following are Jave code examples for showing how to use setDefaultCredentialsProvider() of the org.apache.http.impl.client.HttpClientBuilder class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: teamcity-msteams-notifier   File: MsTeamsNotificationImpl.java   View Source Code Vote up 6 votes
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) {
      this.proxyHost = proxyHost;
      this.proxyPort = proxyPort;
      
if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) {
          HttpClientBuilder clientBuilder = HttpClients.custom()
              .useSystemProperties()
              .setProxy(new HttpHost(proxyHost, proxyPort, "http"));
              
          if (credentials != null) {
              CredentialsProvider credsProvider = new BasicCredentialsProvider();
              credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
              clientBuilder.setDefaultCredentialsProvider(credsProvider);
              Loggers.SERVER.debug("MsTeamsNotification ::using proxy credentials " + credentials.getUserPrincipal().getName());
          }
          
          this.client = clientBuilder.build();
}
  }
 
Example 2
Project: Cognizant-Intelligent-Test-Scripter   File: RemoteProxy.java   View Source Code Vote up 6 votes
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) {

        prop = decrypt(prop);

        String proxyHost = prop.getProperty("proxyHost");
        int proxyPort = Integer.valueOf(prop.getProperty("proxyPort"));
        String proxyUserDomain = prop.getProperty("proxyUserDomain");
        String proxyUser = prop.getProperty("proxyUser");
        String proxyPassword = prop.getProperty("proxyPassword");

        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain));
        if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
            credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
        builder.setProxy(proxy);
        builder.setDefaultCredentialsProvider(credsProvider);
        HttpClient.Factory factory = new SimpleHttpClientFactory(builder);
        return new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);

    }
 
Example 3
Project: Reer   File: HttpClientConfigurer.java   View Source Code Vote up 5 votes
public void configure(HttpClientBuilder builder) {
    SystemDefaultCredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider();
    configureSslSocketConnectionFactory(builder, httpSettings.getSslContextFactory());
    configureAuthSchemeRegistry(builder);
    configureCredentials(builder, credentialsProvider, httpSettings.getAuthenticationSettings());
    configureProxy(builder, credentialsProvider, httpSettings);
    configureUserAgent(builder);
    builder.setDefaultCredentialsProvider(credentialsProvider);
}
 
Example 4
Project: camunda-task-dispatcher   File: ExternalTaskRestServiceImpl.java   View Source Code Vote up 5 votes
@PostConstruct
public void init() {
    objectMapper = new ObjectMapper();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    if (StringUtils.hasText(camundaUser)) {
        final BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(camundaUser, camundaPass));
        clientBuilder.setDefaultCredentialsProvider(provider);
    }
    httpClient = clientBuilder.build();
}
 
Example 5
Project: cf-java-client-sap   File: RestUtil.java   View Source Code Vote up 5 votes
public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean
        trustSelfSignedCerts) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();

    if (trustSelfSignedCerts) {
        httpClientBuilder.setSslcontext(buildSslContext());
        httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

    if (httpProxyConfiguration != null) {
        HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort());
        httpClientBuilder.setProxy(proxy);

        if (httpProxyConfiguration.isAuthRequired()) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(
                    new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()),
                    new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(), httpProxyConfiguration
                            .getPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpClientBuilder.setRoutePlanner(routePlanner);
    }

    HttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

    return requestFactory;
}
 
Example 6
Project: httpclient   File: RestClient.java   View Source Code Vote up 5 votes
private HttpClient createHttpClient(Authentication auth, String verify, HttpHost target, Boolean postRedirects,
		String password, TrustStrategy keystoreTrustStrategy, HostnameVerifier keystoreHostnameVerifier,
		Proxy proxy) {
	Certificate certificate = new Certificate();
	Auth authHelper = new Auth();
	HttpClientBuilder httpClientBuilder = WinHttpClients.custom();
	Builder requestConfig = RequestConfig.custom();
	requestConfig.setCookieSpec(CookieSpecs.DEFAULT);

	logger.debug("Verify value: " + verify);
	logger.debug((new File(verify).getAbsolutePath()));

	if (new File(verify).exists()) {
		logger.debug("Loading custom keystore");
		httpClientBuilder.setSSLSocketFactory(
				certificate.allowAllCertificates(certificate.createCustomKeyStore(verify.toString(), password),
						password, keystoreTrustStrategy, keystoreHostnameVerifier));
	} else if (!Boolean.parseBoolean(verify.toString())) {
		logger.debug("Allowing all certificates");
		httpClientBuilder.setSSLSocketFactory(certificate.allowAllCertificates(null));
	}

	if (auth.isAuthenticable()) {
		httpClientBuilder.setDefaultCredentialsProvider(authHelper.getCredentialsProvider(auth, target));
	}

	if (proxy != null && proxy.isInUse()) {
		logger.debug("Enabling proxy");
		if (proxy.isAuthenticable()) {
			logger.debug("Setting proxy credentials");
			httpClientBuilder.setDefaultCredentialsProvider(
					authHelper.getCredentialsProvider(proxy.getAuth(), proxy.getHttpHost()));
		}
		requestConfig.setProxy(proxy.getHttpHost());
	}

	if (postRedirects) {
		httpClientBuilder.setRedirectStrategy(new CustomRedirectStrategy());
	}
	httpClientBuilder.setDefaultRequestConfig(requestConfig.build());

	return httpClientBuilder.build();
}
 
Example 7
Project: ats-framework   File: HttpClient.java   View Source Code Vote up 5 votes
/**
 * Set up authentication for HTTP Basic/HTTP Digest/SPNEGO.
 *
 * @param httpClientBuilder The client builder
 * @return The context
 * @throws HttpException
 */
private void setupAuthentication( HttpClientBuilder httpClientBuilder ) throws HttpException {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                                 new UsernamePasswordCredentials(username, password));
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);

    if (authType == AuthType.always) {
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();

        HttpHost target = new HttpHost(host, port, isOverSsl
                                                             ? "https"
                                                             : "http");
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        httpContext.setAuthCache(authCache);
    } else {
        if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) {
            GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile);
            AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName,
                                                             kerberosServicePrincipalType);
            final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
                                                                                   .register(AuthSchemes.SPNEGO,
                                                                                             nsf)
                                                                                   .build();
            httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        }
    }
}
 
Example 8
Project: ARCLib   File: SpnegoHelper.java   View Source Code Vote up 5 votes
public static void addSpnego(HttpClientBuilder clientBuilder) {
    //Add spnego http header processor
    Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
    clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    //There has to be at least this dummy credentials provider or apache http client gives up
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullCredentials());
    clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
 
Example 9
Project: spring-cloud-dashboard   File: HttpClientUtils.java   View Source Code Vote up 5 votes
/**
 * 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 10
Project: smn-sdk-java   File: HttpUtil.java   View Source Code Vote up 5 votes
/**
 * Construct httpclient with SSL protocol
 *
 * @param clientConfiguration the client configuration
 * @return {@code CloseableHttpClient}
 * @throws Exception
 */
public static CloseableHttpClient getHttpClient(ClientConfiguration clientConfiguration) throws Exception {
    if (clientConfiguration == null) {
        clientConfiguration = new ClientConfiguration();
    }

    SSLConnectionSocketFactory sslSocketFactory = createSslConnectionSocketFactory(clientConfiguration);
    HttpClientBuilder builder = HttpClients.custom();

    // set proxy
    String proxyHost = clientConfiguration.getProxyHost();
    int proxyPort = clientConfiguration.getProxyPort();

    if (!StringUtils.isEmpty(proxyHost) && proxyPort > 0) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        builder.setProxy(proxy);

        String username = clientConfiguration.getProxyUserName();
        String password = clientConfiguration.getProxyPassword();

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            AuthScope authscope = new AuthScope(proxy);
            Credentials credentials = new UsernamePasswordCredentials(username,
                    password);
            credentialsProvider.setCredentials(authscope, credentials);
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    builder.setUserAgent(VersionUtil.getDefaultUserAgent());
    CloseableHttpClient httpclient = builder.setSSLSocketFactory(sslSocketFactory).build();
    return httpclient;
}
 
Example 11
Project: aws-sdk-java-v2   File: ApacheHttpClientFactory.java   View Source Code Vote up 5 votes
private void addProxyConfig(HttpClientBuilder builder,
                            ProxyConfiguration proxyConfiguration) {
    if (isProxyEnabled(proxyConfiguration)) {

        LOG.info("Configuring Proxy. Proxy Host: " + proxyConfiguration.endpoint());

        builder.setRoutePlanner(new SdkProxyRoutePlanner(proxyConfiguration.endpoint().getHost(),
                                                         proxyConfiguration.endpoint().getPort(),
                                                         proxyConfiguration.nonProxyHosts()));

        if (isAuthenticatedProxy(proxyConfiguration)) {
            builder.setDefaultCredentialsProvider(ApacheUtils.newProxyCredentialsProvider(proxyConfiguration));
        }
    }
}
 
Example 12
Project: java-restclient   File: HTTPCBuilder.java   View Source Code Vote up 5 votes
private void addProxy(RESTPool pool, HttpClientBuilder builder) {
    if (pool.getProxy() == null) return;

    Proxy proxy = pool.getProxy();

    if (proxy.getUsername() != null) {
        CredentialsProvider provider = makeProxyCredentialsProvider(proxy);
        builder.setDefaultCredentialsProvider(provider);
    }

    HttpHost proxyHost = new HttpHost(proxy.getHostname(), proxy.getPort());
    builder.setRoutePlanner(new DefaultProxyRoutePlanner(proxyHost));
}
 
Example 13
Project: ibm-cos-sdk-java   File: ApacheHttpClientFactory.java   View Source Code Vote up 5 votes
private void addProxyConfig(HttpClientBuilder builder,
                            HttpClientSettings settings) {
    if (settings.isProxyEnabled()) {

        LOG.info("Configuring Proxy. Proxy Host: " + settings.getProxyHost() + " " +
                "Proxy Port: " + settings.getProxyPort());

        builder.setRoutePlanner(new SdkProxyRoutePlanner(
                settings.getProxyHost(), settings.getProxyPort(), settings.getNonProxyHosts()));

        if (settings.isAuthenticatedProxy()) {
            builder.setDefaultCredentialsProvider(ApacheUtils.newProxyCredentialsProvider(settings));
        }
    }
}
 
Example 14
Project: xtf   File: HttpClient.java   View Source Code Vote up 4 votes
private CloseableHttpClient build(final Consumer<HttpClientBuilder> customizeBuilder) throws IOException {
	LOGGER.debug("HTTP {} {}", request, url);
	if (httpClient != null) {
		LOGGER.debug("Existing HttpClient re-used");
		return httpClient;
	}
	if (sslsf == null) {
		sslsf = createSSLConnectionSocketFactory(null, null, false);
	}

	HttpClientBuilder builder = HttpClients.custom()
			.setRetryHandler(new StandardHttpRequestRetryHandler(3, true) {
				@Override
				public boolean retryRequest(IOException exception,
						int executionCount, HttpContext context) {
					try {
						TimeUnit.SECONDS.sleep(3);
					} catch (InterruptedException e) {
					}
					return super.retryRequest(exception, executionCount,
							context);
				}
			}).setSSLSocketFactory(sslsf);
	if (username != null) {
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(
				new AuthScope(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort()),
				new UsernamePasswordCredentials(username, password));

		builder.setDefaultCredentialsProvider(credsProvider);
	}
	if (disableRedirect) {
		builder.disableRedirectHandling();
	}

	addPreemptiveAuthorizationHeaders();

	if (customizeBuilder != null) {
		customizeBuilder.accept(builder);
	}
	if (!cookies.isEmpty()) {
		final CookieStore cookieStore = new BasicCookieStore();
		cookies.entrySet().stream().map(x -> new BasicClientCookie(x.getKey(), x.getValue())).forEach(cookieStore::addCookie);
		builder.setDefaultCookieStore(cookieStore);
	}
	return builder.build();
}
 
Example 15
Project: microprofile-health   File: SimpleHttp.java   View Source Code Vote up 4 votes
protected Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {

        StringBuilder content = new StringBuilder();
        int code;

        try {

            HttpClientBuilder builder = HttpClientBuilder.create();
            if (!followRedirects) {
                builder.disableRedirectHandling();
            }

            if (useAuth) {
                CredentialsProvider provider = new BasicCredentialsProvider();
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
                provider.setCredentials(AuthScope.ANY, credentials);
                builder.setDefaultCredentialsProvider(provider);
            }

            HttpClient client = builder.build();

            HttpResponse response = client.execute(new HttpGet(theUrl));
            code = response.getStatusLine().getStatusCode();

            if (response.getEntity() != null) {

                BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent())
                );

                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    content.append(line + "\n");
                }
                bufferedReader.close();
            }

        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }

        return new Response(code, content.toString());
    }
 
Example 16
Project: pardot-java-client   File: HttpClientRestClient.java   View Source Code Vote up 4 votes
/**
 * Initialization method.  This takes in the configuration and sets up the underlying
 * http client appropriately.
 * @param configuration The user defined configuration.
 */
@Override
public void init(final Configuration configuration) {
    // Save reference to configuration
    this.configuration = configuration;

    // Create default SSLContext
    final SSLContext sslcontext = SSLContexts.createDefault();

    // Allow TLSv1 protocol only
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.getDefaultHostnameVerifier()
    );

    // Setup client builder
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder
        // Pardot disconnects requests after 120 seconds.
        .setConnectionTimeToLive(130, TimeUnit.SECONDS)
        .setSSLSocketFactory(sslsf);

    // Define our RequestConfigBuilder
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    // If we have a configured proxy host
    if (configuration.getProxyHost() != null) {
        // Define proxy host
        final HttpHost proxyHost = new HttpHost(
            configuration.getProxyHost(),
            configuration.getProxyPort(),
            configuration.getProxyScheme()
        );

        // If we have proxy auth enabled
        if (configuration.getProxyUsername() != null) {
            // Create credential provider
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(configuration.getProxyHost(), configuration.getProxyPort()),
                new UsernamePasswordCredentials(configuration.getProxyUsername(), configuration.getProxyPassword())
            );

            // Attach Credentials provider to client builder.
            clientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        // Attach Proxy to request config builder
        requestConfigBuilder.setProxy(proxyHost);
    }

    // Attach default request config
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    // build http client
    httpClient = clientBuilder.build();
}