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

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#setDefaultCredentialsProvider() . 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: PGPKeysServerClient.java    From pgpverify-maven-plugin with Apache License 2.0 7 votes vote down vote up
protected HttpClientBuilder setupProxy(HttpClientBuilder clientBuilder) {
    if (this.proxy == null) {
        return clientBuilder;
    }

    if (proxy.getUsername() != null && !proxy.getUsername().isEmpty() &&
        proxy.getPassword() != null && !proxy.getPassword().isEmpty()) {
        clientBuilder.setProxyAuthenticationStrategy(ProxyAuthenticationStrategy.INSTANCE);
        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        AuthScope proxyAuthScope = new AuthScope(proxy.getHost(), proxy.getPort());
        UsernamePasswordCredentials proxyAuthentication =
            new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
        basicCredentialsProvider.setCredentials(proxyAuthScope, proxyAuthentication);
        clientBuilder.setDefaultCredentialsProvider(basicCredentialsProvider);
    }
    return clientBuilder;
}
 
Example 2
Source File: DefaultTokenManager.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Add a proxy to the http request if it has been set within settings
 * 
 * @param builder
 * 			Builder used to create the http client
 * @param settings
 * 			Settings which contain any proxy configuration details
 */
public static 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 3
Source File: HttpClientManager.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public CloseableHttpClient build() {
  HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  httpClientBuilder.setConnectionManager( manager );

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  if ( socketTimeout > 0 ) {
    requestConfigBuilder.setSocketTimeout( socketTimeout );
  }
  if ( connectionTimeout > 0 ) {
    requestConfigBuilder.setConnectTimeout( socketTimeout );
  }
  if ( proxy != null ) {
    requestConfigBuilder.setProxy( proxy );
  }
  httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() );

  if ( provider != null ) {
    httpClientBuilder.setDefaultCredentialsProvider( provider );
  }
  if ( redirectStrategy != null ) {
    httpClientBuilder.setRedirectStrategy( redirectStrategy );
  }

  return httpClientBuilder.build();
}
 
Example 4
Source File: DigestAuthHandler.java    From restfiddle with Apache License 2.0 6 votes vote down vote up
public void setCredentialsProvider(RfRequestDTO requestDTO, HttpClientBuilder clientBuilder) {
DigestAuthDTO digestAuthDTO = requestDTO.getDigestAuthDTO();
if (digestAuthDTO == null) {
    return;
}
String userName = digestAuthDTO.getUsername();
String password = digestAuthDTO.getPassword();
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
    return;
}
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
	new UsernamePasswordCredentials(userName, password));

clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
   }
 
Example 5
Source File: HttpRequestHandler.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
private CloseableHttpClient getHttpClient(String url) {
     RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectionTimeout)
.build();
     HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
     httpClientBuilder.setDefaultRequestConfig(requestConfig);
     httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
     httpClientBuilder.setUserAgent(ASQATASUN_USER_AGENT);
     if (isProxySet(url)) {
         LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
         httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
         if (isProxyCredentialSet()) {
             CredentialsProvider credsProvider = new BasicCredentialsProvider();
             credsProvider.setCredentials(
                     new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
                     new UsernamePasswordCredentials(proxyUser, proxyPassword));
             httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
             LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser + " and " + proxyPassword));
         }
     }
     return httpClientBuilder.build();
 }
 
Example 6
Source File: AbstractCheckThread.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected CloseableHttpClient buildHttpClient() {
	HttpClientBuilder httpClientBuilder = HttpClients.custom();
	CredentialsProvider credsProvider = new BasicCredentialsProvider();

	try {
		Credentials credentials = check.getCredentials();
		if (credentials != null) {
			basicAuthentication(httpClientBuilder, credsProvider, credentials);
		}
	} catch (Exception ex) {
		throw new RuntimeException("Could not use credentials");
	}
	// set proxy
	if (check.getHttpProxyUsername() != null && !check.getHttpProxyPassword().isEmpty()) {
		credsProvider.setCredentials(new AuthScope(check.getHttpProxyServer(), check.getHttpProxyPort()),
				new UsernamePasswordCredentials(check.getHttpProxyUsername(), check.getHttpProxyPassword()));
		httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
	}
	return httpClientBuilder.build();
}
 
Example 7
Source File: WxPayServiceApacheHttpImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private HttpClientBuilder createHttpClientBuilder(boolean useKey) throws WxPayException {
  HttpClientBuilder httpClientBuilder = HttpClients.custom();
  if (useKey) {
    this.initSSLContext(httpClientBuilder);
  }

  if (StringUtils.isNotBlank(this.getConfig().getHttpProxyHost())
    && this.getConfig().getHttpProxyPort() > 0) {
    // 使用代理服务器 需要用户认证的代理服务器
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
      new AuthScope(this.getConfig().getHttpProxyHost(), this.getConfig().getHttpProxyPort()),
      new UsernamePasswordCredentials(this.getConfig().getHttpProxyUsername(), this.getConfig().getHttpProxyPassword()));
    httpClientBuilder.setDefaultCredentialsProvider(provider);
  }
  return httpClientBuilder;
}
 
Example 8
Source File: InfluxDBPublisher.java    From beam with Apache License 2.0 5 votes vote down vote up
private static HttpClientBuilder provideHttpBuilder(final InfluxDBSettings settings) {
  final HttpClientBuilder builder = HttpClientBuilder.create();

  if (isNoneBlank(settings.userName, settings.userPassword)) {
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
        AuthScope.ANY, new UsernamePasswordCredentials(settings.userName, settings.userPassword));
    builder.setDefaultCredentialsProvider(provider);
  }

  return builder;
}
 
Example 9
Source File: ServiceNowExecution.java    From service-now-plugin with MIT License 5 votes vote down vote up
private CloseableHttpClient authenticate(HttpClientBuilder clientBuilder, HttpRequestBase requestBase, HttpContext httpContext) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
            new AuthScope(requestBase.getURI().getHost(), requestBase.getURI().getPort()),
            CredentialsUtil.readCredentials(credentials, vaultConfiguration));
    clientBuilder.setDefaultCredentialsProvider(provider);

    AuthCache authCache = new BasicAuthCache();
    authCache.put(URIUtils.extractHost(requestBase.getURI()), new BasicScheme());
    httpContext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    return clientBuilder.build();
}
 
Example 10
Source File: WebServicesClient.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
public WebServicesClient(ClientConfig config)
{
  if (SecurityUtils.isHadoopWebSecurityEnabled()) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(connectionManager);
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    httpClientBuilder.setDefaultAuthSchemeRegistry(authRegistry);
    ApacheHttpClient4Handler httpClientHandler = new ApacheHttpClient4Handler(httpClientBuilder.build(), new BasicCookieStore(), false);
    client = new Client(httpClientHandler, config);
  } else {
    client = Client.create(config);
  }
}
 
Example 11
Source File: HttpClientFactory.java    From rug-cli with GNU General Public License v3.0 5 votes vote down vote up
private static void configureProxy(HttpClientBuilder builder, String url) {
    List<Proxy> proxies = ProxySelector.getDefault().select(URI.create(url));
    if (!proxies.isEmpty()) {
        Optional<Proxy> proxy = proxies.stream().filter(p -> p.type().equals(Proxy.Type.HTTP))
                .findFirst();
        if (proxy.isPresent()) {
            InetSocketAddress address = (InetSocketAddress) proxy.get().address();
            builder.setProxy(new HttpHost(address.getHostName(), address.getPort()));

            try {
                PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
                        address.getHostName(), null, address.getPort(),
                        (url.startsWith("https://") ? "https" : "http"),
                        "Credentials for proxy " + proxy, null, new URL(url),
                        Authenticator.RequestorType.PROXY);
                if (auth != null) {
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(address.getHostName(), address.getPort()),
                            new UsernamePasswordCredentials(auth.getUserName(),
                                    String.valueOf(auth.getPassword())));
                    builder.setDefaultCredentialsProvider(credsProvider);
                }
            }
            catch (MalformedURLException e) {
            }
        }
    }
}
 
Example 12
Source File: RestUtil.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
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();

    return new HttpComponentsClientHttpRequestFactory(httpClient);
}
 
Example 13
Source File: HttpClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 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 14
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    RequestConfig.Builder requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to connect to remote host
            .setSocketTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to retrieve data from remote host
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
    client.setDefaultRequestConfig(requestConfig.build());

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData);
    }

    return client;
}
 
Example 15
Source File: HttpDataService.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void setAuthentication(Map<String, Object> parameters, HttpClientBuilder clientBuilder)
{
	String username = getUsername(parameters);
	if (username != null)
	{
		String password = getPassword(parameters);
		
		BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		//FIXME proxy authentication?
		credentialsProvider.setCredentials(
				new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
				new UsernamePasswordCredentials(username, password));
		clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
	}
}
 
Example 16
Source File: HttpClientManager.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public CloseableHttpClient build() {
  HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
  httpClientBuilder.setConnectionManager( manager );

  RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
  if ( socketTimeout > 0 ) {
    requestConfigBuilder.setSocketTimeout( socketTimeout );
  }
  if ( connectionTimeout > 0 ) {
    requestConfigBuilder.setConnectTimeout( socketTimeout );
  }
  if ( proxy != null ) {
    requestConfigBuilder.setProxy( proxy );
  }
  if ( cookieSpec != null ) {
    requestConfigBuilder.setCookieSpec( cookieSpec );
  }
  if ( maxRedirects > 0 ) {
    requestConfigBuilder.setMaxRedirects( maxRedirects );
  }
  if ( allowCircularRedirects ) {
    requestConfigBuilder.setCircularRedirectsAllowed( true );
  }
  if ( !rejectRelativeRedirect ) {
    requestConfigBuilder.setRelativeRedirectsAllowed( true );
  }

  // RequestConfig built
  httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() );

  if ( provider != null ) {
    httpClientBuilder.setDefaultCredentialsProvider( provider );
  }
  if ( redirectStrategy != null ) {
    httpClientBuilder.setRedirectStrategy( redirectStrategy );
  }

  return httpClientBuilder.build();
}
 
Example 17
Source File: WebApiTestServer.java    From baleen with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient createClient(String username, String password) {
  HttpClientBuilder builder = HttpClientBuilder.create();

  if (username != null && password != null) {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
        AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    builder.setDefaultCredentialsProvider(credentialsProvider);
  }

  return builder.build();
}
 
Example 18
Source File: TCKBase.java    From smallrye-health with Apache License 2.0 4 votes vote down vote up
private 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 19
Source File: AbstractCheckThread.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void basicAuthentication(HttpClientBuilder httpClientBuilder, CredentialsProvider credsProvider, Credentials credentials) throws URISyntaxException {
	URI uri = new URI(check.getUrl());
	credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()));
	httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
}
 
Example 20
Source File: HttpClientUtils.java    From ais-sdk with Apache License 2.0 4 votes vote down vote up
public static CloseableHttpClient acceptsUntrustedCertsHttpClient(boolean withProxy, ProxyHostInfo hostInfo, int connectionTimeout, int connectionRequestTimeout, int socketTimeout)
		throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
	HttpClientBuilder b = HttpClientBuilder.create();
	
	/**
	 * set http proxy
	 */
	
	b.setDefaultRequestConfig( 
			RequestConfig.custom().setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build()
			);
	
	if(withProxy){
		HttpHost proxy=new HttpHost(hostInfo.getHostName(),hostInfo.getPort());
		b.setProxy(proxy);
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(
				new AuthScope(proxy.getHostName(), proxy.getPort()),
				new UsernamePasswordCredentials(hostInfo.getUserName(), hostInfo.getPassword()));
		b.setDefaultCredentialsProvider(credsProvider);
	}
	
	SSLContext sslContext = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(null, new TrustStrategy() {
		public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			return true;
		}
	}).build();
	b.setSSLContext(sslContext);
	b.setConnectionTimeToLive(180, TimeUnit.SECONDS);

	HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

	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);
	connMgr.setMaxTotal(200);
	connMgr.setDefaultMaxPerRoute(100);
	b.setConnectionManager(connMgr);
	CloseableHttpClient client = b.build();
	return client;
}