Example usage for org.apache.http.client CredentialsProvider setCredentials

List of usage examples for org.apache.http.client CredentialsProvider setCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider setCredentials.

Prototype

void setCredentials(AuthScope authscope, Credentials credentials);

Source Link

Document

Sets the Credentials credentials for the given authentication scope.

Usage

From source file:com.jkoolcloud.tnt4j.streams.inputs.RestStream.java

private static String executeRequest(HttpClient client, HttpUriRequest req, String username, String password)
        throws IOException {
    HttpResponse response;/*from   w  w  w .  java2  s. c o  m*/

    if (StringUtils.isNotEmpty(username)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(req.getURI().getAuthority(), DEFAULT_AUTH_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        // context.setAuthSchemeRegistry(authRegistry);
        // context.setAuthCache(authCache);

        response = client.execute(req, context);
    } else {
        response = client.execute(req);
    }

    int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
        throw new HttpResponseException(responseCode, response.getStatusLine().getReasonPhrase());
    }

    String respStr = EntityUtils.toString(response.getEntity(), Utils.UTF8);

    return respStr;
}

From source file:v2.service.generic.library.utils.HttpClientUtil.java

public static HttpClient createHttpClientWithAuth(String credential, String principle) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(credential, principle);
    provider.setCredentials(AuthScope.ANY, credentials);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build();
    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
            .setDefaultRequestConfig(requestConfig).build();
    return httpclient;
}

From source file:co.aurasphere.botmill.skype.util.network.NetworkUtils.java

/**
 * Send./*from   w w  w.ja  v a  2 s  .c  om*/
 *
 * @param request the request
 * @return the string
 */
private static String send(HttpRequestBase request) {

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(null, null);

    provider.setCredentials(AuthScope.ANY, credentials);
    CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    logger.debug(request.getRequestLine().toString());
    HttpResponse httpResponse = null;
    String response = null;
    try {
        httpResponse = httpClient.execute(request);
        response = logResponse(httpResponse);
    } catch (Exception e) {
        logger.error("Error during HTTP connection to Kik: ", e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("Error while closing HTTP connection: ", e);
        }
    }
    return response;
}

From source file:annis.libgui.Helper.java

/**
 * Creates an authentificiated REST client 
 * @param userName/* ww w .  java  2 s.c o m*/
 * @param password
 * @return A newly created client.
 */
public static Client createRESTClient(String userName, String password) {

    DefaultApacheHttpClient4Config rc = new DefaultApacheHttpClient4Config();
    rc.getClasses().add(SaltProjectProvider.class);

    rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER,
            new ThreadSafeClientConnManager());

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

        rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, credentialsProvider);
        rc.getProperties().put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, true);

    }

    Client c = ApacheHttpClient4.create(rc);
    return c;
}

From source file:com.clonephpscrapper.utility.FetchPageWithProxy.java

public static String fetchPageSourcefromClientGoogle(URI newurl) throws IOException, InterruptedException {

    int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope("195.154.161.103", portNo),
            new UsernamePasswordCredentials("mongoose", "Fjh30fi"));
    HttpHost proxy = new HttpHost("195.154.161.103", portNo);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {/*from w  w w. j ava  2s  . co  m*/
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Connection", "keep-alive");

        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    System.out.println("PROX FAILURE");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * Creates an HttpClient//from   w  w  w .j  a  va 2  s.com
 * 
 * @param auth {@link AuthScope} object specifying the scope of this client
 * @param creds {@link Credentials} for the client
 * @return {@link HttpClient} client to make http requests
 */
public static CloseableHttpClient createHttpClient(AuthScope auth, Credentials creds) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(auth, creds);
    CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    return client;
}

From source file:com.clonephpscrapper.utility.FetchPageWithProxy.java

public static String fetchPage(URI newurl) throws IOException, InterruptedException {

    int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope("195.154.161.103", portNo),
            new UsernamePasswordCredentials("mongoose", "Fjh30fi"));
    HttpHost proxy = new HttpHost("195.154.161.103", portNo);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {/*  w ww.  j  ava2  s .co  m*/
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("GET ", "http://clonephp.com/");
        httpget.addHeader("Host", "clonephp.com");
        httpget.addHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
        httpget.addHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.8");
        httpget.addHeader("Connection", "keep-alive");
        //            httpget.addHeader("Cookie", "_ym_uid=14523228509491377; _gat=1; _ym_isad=0; _ga=GA1.2.438893798.1452322850; _ym_visorc_26745633=b; last-featured-visit-time=1452323357912\n" +
        //"If-None-Match: W/\"10d86-1fKww4Zqud7NjVeuSjZKEw\"");

        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    System.out.println("PROX FAILURE");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:org.nuxeo.connect.registration.RegistrationHelper.java

protected static HttpClientContext getHttpClientContext(String url, String login, String password) {
    HttpClientContext context = HttpClientContext.create();

    // Set credentials provider
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    if (login != null) {
        Credentials ba = new UsernamePasswordCredentials(login, password);
        credentialsProvider.setCredentials(AuthScope.ANY, ba);
    }//from www.ja v  a  2  s. co m
    context.setCredentialsProvider(credentialsProvider);

    // Create AuthCache instance for preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    try {
        authCache.put(URIUtils.extractHost(new URI(url)), basicAuth);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    context.setAuthCache(authCache);

    // Create request configuration
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(10000);

    // Configure the http proxy if needed
    ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, url);

    context.setRequestConfig(requestConfigBuilder.build());
    return context;
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClientContext createContext(URL endpoint, String username, String password, int port) {
    HttpClientContext context = null;/* w w w . j ava  2  s  .c o m*/
    HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol());
    if (username != null && password != null) {

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(username, password));

        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
        AuthCache authCache = new BasicAuthCache();
        authCache.put(target, new BasicScheme());

        // Add AuthCache to the execution context
        context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    } else {
        context = null;
    }
    return context;
}

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClientFactory.java

private static CredentialsProvider getCredentialsProvider(ElasticsearchClientConfig esClientConfig) {
    Optional<Entry<String, String>> credentials = esClientConfig.getCredentials();
    if (credentials.isPresent()) {
        LOG.info("Found auth credentials - setting up user/pass authenticated client connection for ES.");
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials(credentials.get().getKey(),
                credentials.get().getValue());
        credentialsProvider.setCredentials(AuthScope.ANY, upcredentials);
        return credentialsProvider;
    } else {//from  w  w  w  .ja v a2s . co  m
        LOG.info(
                "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection.");
        return null;
    }
}