Example usage for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider

List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider.

Prototype

public final HttpClientBuilder setDefaultCredentialsProvider(final CredentialsProvider credentialsProvider) 

Source Link

Document

Assigns default CredentialsProvider instance which will be used for request execution if not explicitly set in the client execution context.

Usage

From source file:es.auth.plugin.AbstractUnitTest.java

protected final JestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();
    // Construct a new Jest client according to configuration via factory
    final JestClientFactory factory1 = new JestClientFactory();
    factory1.setHttpClientConfig(clientConfig1);
    final JestHttpClient c = factory1.getObject();
    final HttpClientBuilder hcb = HttpClients.custom();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
    hcb.setDefaultCredentialsProvider(credsProvider);
    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());
    final CloseableHttpClient httpClient = hcb.build();
    c.setHttpClient(httpClient);/*  w  w w. j  a  va 2  s  . co m*/
    return c;
}

From source file:io.github.bonigarcia.wdm.WdmHttpClient.java

private WdmHttpClient(String proxyUrl, String proxyUser, String proxyPass) {
    HttpHost proxyHost = createProxyHttpHost(proxyUrl);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (proxyHost != null) {
        builder.setProxy(proxyHost);// w ww  .  j  a v a  2s  .  c o m
        BasicCredentialsProvider credentialsProvider = createBasicCredentialsProvider(proxyUrl, proxyUser,
                proxyPass, proxyHost);
        builder.setDefaultCredentialsProvider(credentialsProvider);
    }
    this.httpClient = builder.build();
}

From source file:org.jboss.teiid.quickstart.PortfolioClient.java

public void resteasyHttpBackendClient() {

    System.out.println("\nResteasy Client API with HTTP client as engine");

    HttpHost targetHost = new HttpHost("localhost", 8080, "http");

    // 1. Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // 2. Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // 3. Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    // 4. Create client executor and proxy
    HttpClientBuilder builder = HttpClientBuilder.create();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope scope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
    credsProvider.setCredentials(scope, credentials);
    builder.setDefaultCredentialsProvider(credsProvider);
    HttpClient httpClient = builder.build();

    // 5. Create ResteasyClient with http client as engine
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext);
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();

    // 6. Execute Rest call via ResteasyClient
    String authString = getBasicAuthentication();
    for (String api : apis) {
        ResteasyWebTarget target = client.target(api);
        Response response = target.request().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML)
                .header(HttpHeaders.AUTHORIZATION, authString).get();
        if (response.getStatus() == 200) {
            String value = response.readEntity(String.class);
            System.out.println(value);
            response.close();/*w w  w  .  ja v a2  s  .  co  m*/
        } else {
            handleError(response);
        }
    }
}

From source file:org.miloss.fgsms.presentation.StatusHelper.java

/**
 * determines if an fgsms service is currently accessible. not for use
 * with other services.//from   ww  w .  ja  v  a 2s . c o m
 *
 * @param endpoint
 * @return
 */
public String sendGetRequest(String endpoint) {
    //   String result = null;
    if (endpoint.startsWith("http")) {
        // Send a GET request to the servlet
        try {

            URL url = new URL(endpoint);
            int port = url.getPort();
            if (port <= 0) {
                if (endpoint.startsWith("https:")) {
                    port = 443;
                } else {
                    port = 80;
                }
            }

            HttpClientBuilder create = HttpClients.custom();

            if (mode == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(url.getHost(), port),
                        new UsernamePasswordCredentials(username, Utility.DE(password)));
                create.setDefaultCredentialsProvider(credsProvider);
                ;

            }
            CloseableHttpClient c = create.build();

            CloseableHttpResponse response = c.execute(new HttpHost(url.getHost(), port),
                    new HttpGet(endpoint));

            c.close();
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                return "OK";
            }
            return String.valueOf(status);

        } catch (Exception ex) {
            Logger.getLogger(Helper.class).log(Level.WARN,
                    "error fetching http doc from " + endpoint + ex.getLocalizedMessage());
            return "offline";
        }
    } else {
        return "undeterminable";
    }
}

From source file:com.ksc.http.apache.client.impl.ApacheHttpClientFactory.java

private void addProxyConfig(HttpClientBuilder builder, HttpClientSettings settings) {
    if (isProxyEnabled(settings)) {

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

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

        if (isAuthenticatedProxy(settings)) {
            builder.setDefaultCredentialsProvider(ApacheUtils.newProxyCredentialsProvider(settings));
        }/*  www. j  a v  a2s . c  o  m*/
    }
}

From source file:org.eclipse.microprofile.health.tck.SimpleHttp.java

protected Response getUrlContents(String theUrl, boolean useAuth, boolean followRedirects) {

    StringBuilder content = new StringBuilder();
    int code;/*from www .  j a  va2  s.c o m*/

    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());
}

From source file:org.opensextant.xtext.collectors.sharepoint.SharepointClient.java

/**
 * Sharepoint requires NTLM. This client requires a non-null user/passwd/domain.
 * /*from  w ww.  j  a va 2s  .  com*/
 */
@Override
public HttpClient getClient() {

    if (currentConn != null) {
        return currentConn;
    }

    HttpClientBuilder clientHelper = HttpClientBuilder.create();

    if (proxyHost != null) {
        clientHelper.setProxy(proxyHost);
    }

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();

    CredentialsProvider creds = new BasicCredentialsProvider();
    creds.setCredentials(AuthScope.ANY, new NTCredentials(user, passwd, server, domain));
    clientHelper.setDefaultCredentialsProvider(creds);
    HttpClient httpClient = clientHelper.setDefaultRequestConfig(globalConfig).build();

    return httpClient;

}

From source file:org.neo4j.jdbc.http.driver.CypherExecutor.java

/**
 * Default constructor./*from  w  ww.  j  a va2  s.c  o m*/
 *
 * @param host       Hostname of the Neo4j instance.
 * @param port       HTTP port of the Neo4j instance.
 * @param secure    If the connection used SSL.
 * @param properties Properties of the url connection.
 */
public CypherExecutor(String host, Integer port, Boolean secure, Properties properties) throws SQLException {
    this.secure = secure;

    // Create the http client builder
    HttpClientBuilder builder = HttpClients.custom();

    // Adding authentication to the http client if needed
    CredentialsProvider credentialsProvider = getCredentialsProvider(host, port, properties);
    if (credentialsProvider != null)
        builder.setDefaultCredentialsProvider(credentialsProvider);

    // Setting user-agent
    String userAgent = properties.getProperty("useragent");
    builder.setUserAgent("Neo4j JDBC Driver" + (userAgent != null ? " via " + userAgent : ""));
    // Create the http client
    this.http = builder.build();

    // Create the url endpoint
    this.transactionUrl = createTransactionUrl(host, port, secure);

    // Setting autocommit
    this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true")));
}

From source file:com.smartling.api.sdk.util.HttpProxyUtils.java

/**
 * Get an HttpClient given a proxy config if any
 * @param proxyConfiguration configuration of proxy to use
 * @return org.apache.http.impl.client.CloseableHttpClient
 *///from w w w  .j ava2s . c o  m
public CloseableHttpClient getHttpClient(final ProxyConfiguration proxyConfiguration) {
    HttpClientBuilder httpClientBuilder = getHttpClientBuilder();

    if (proxyAuthenticationRequired(proxyConfiguration)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                new AuthScope(proxyConfiguration.getHost(), proxyConfiguration.getPort()),
                new UsernamePasswordCredentials(proxyConfiguration.getUsername(),
                        proxyConfiguration.getPassword()));

        httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    return httpClientBuilder.build();
}