Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

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

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:es.tsb.ltba.nomhad.example.ClientWithResponseHandler.java

public final static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient = wrapClient(httpclient);
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("A100", "123456"));

    try {/*  w  w  w.  jav a  2  s .co  m*/
        HttpGet httpget = new HttpGet(NOMHAD_URL_HEADER + "A100" + OBSERVATIONS_REQUEST);

        HttpPost httppost = new HttpPost(NOMHAD_URL_HEADER + "A100" + OBSERVATIONS_REQUEST);
        httppost.setEntity(new StringEntity(BODY_TEST));
        System.out.println("executing request " + httpget.getURI());

        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:httpclient.client.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80),
            new UsernamePasswordCredentials("username", "password"));

    BasicHttpContext localcontext = new BasicHttpContext();
    // Generate DIGEST scheme object, initialize it and stick it to 
    // the local execution context
    DigestScheme digestAuth = new DigestScheme();
    // Suppose we already know the realm name
    digestAuth.overrideParamter("realm", "some realm");
    // Suppose we already know the expected nonce value 
    digestAuth.overrideParamter("nonce", "whatever");
    localcontext.setAttribute("preemptive-auth", digestAuth);

    // Add as the first request interceptor
    httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);
    // Add as the last response interceptor
    httpclient.addResponseInterceptor(new PersistentDigest());

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

    HttpGet httpget = new HttpGet("/");

    System.out.println("executing request: " + httpget.getRequestLine());
    System.out.println("to target: " + targetHost);

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            entity.consumeContent();//from   w ww  . ja v  a2s . c  om
        }
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.hsbc.frc.SevenHero.ClientPreemptiveBasicAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost proxy = new HttpHost("133.13.162.149", 8080, "http");
    HttpHost targetHost = new HttpHost("pt.3g.qq.com");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from www.ja va  2s  .  co m
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("username", "password"));

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

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        HttpGet httpget = new HttpGet("/");

        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("to target: " + targetHost);

        for (int i = 0; i < 3; i++) {
            HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.datacleaner.cluster.http.SimpleMainAppForManualTesting.java

public static void main(String[] args) throws Throwable {

    // create a HTTP BASIC enabled HTTP client
    final DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    final List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);//from   w  w w .j a  va2  s . c  om
    authpref.add(AuthPolicy.DIGEST);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    credentialsProvider.setCredentials(new AuthScope("localhost", 8080), credentials);
    credentialsProvider.setCredentials(new AuthScope("localhost", 9090), credentials);

    // register endpoints
    final List<String> slaveEndpoints = new ArrayList<String>();
    slaveEndpoints.add("http://localhost:8080/DataCleaner-monitor/repository/DC/cluster_slave_endpoint");
    slaveEndpoints.add("http://localhost:9090/DataCleaner-monitor/repository/DC/cluster_slave_endpoint");

    final HttpClusterManager clusterManager = new HttpClusterManager(httpClient, slaveEndpoints);

    final DataCleanerConfiguration configuration = ClusterTestHelper.createConfiguration("manual_test", false);

    // build a job that concats names and inserts the concatenated names
    // into a file
    final AnalysisJobBuilder jobBuilder = new AnalysisJobBuilder(configuration);
    jobBuilder.setDatastore("orderdb");
    jobBuilder.addSourceColumns("CUSTOMERS.CUSTOMERNUMBER", "CUSTOMERS.CUSTOMERNAME",
            "CUSTOMERS.CONTACTFIRSTNAME", "CUSTOMERS.CONTACTLASTNAME");

    AnalyzerComponentBuilder<CompletenessAnalyzer> completeness = jobBuilder
            .addAnalyzer(CompletenessAnalyzer.class);
    completeness.addInputColumns(jobBuilder.getSourceColumns());
    completeness.setConfiguredProperty("Conditions",
            new CompletenessAnalyzer.Condition[] { CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL });

    AnalysisJob job = jobBuilder.toAnalysisJob();
    jobBuilder.close();

    AnalysisResultFuture result = new DistributedAnalysisRunner(configuration, clusterManager).run(job);

    if (result.isErrornous()) {
        throw result.getErrors().get(0);
    }

    final List<AnalyzerResult> results = result.getResults();
    for (AnalyzerResult analyzerResult : results) {
        System.out.println("result:" + analyzerResult);
        if (analyzerResult instanceof CompletenessAnalyzerResult) {
            int invalidRowCount = ((CompletenessAnalyzerResult) analyzerResult).getInvalidRowCount();
            System.out.println("invalid records found: " + invalidRowCount);
        } else {
            System.out.println("class: " + analyzerResult.getClass().getName());
        }
    }
}

From source file:org.eobjects.analyzer.cluster.http.SimpleMainAppForManualTesting.java

public static void main(String[] args) throws Throwable {

    // create a HTTP BASIC enabled HTTP client
    final DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    final List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);/*  w  w w .  j  av  a 2s  . c  o  m*/
    authpref.add(AuthPolicy.DIGEST);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    credentialsProvider.setCredentials(new AuthScope("localhost", 8080), credentials);
    credentialsProvider.setCredentials(new AuthScope("localhost", 9090), credentials);

    // register endpoints
    final List<String> slaveEndpoints = new ArrayList<String>();
    slaveEndpoints.add("http://localhost:8080/DataCleaner-monitor/repository/DC/cluster_slave_endpoint");
    slaveEndpoints.add("http://localhost:9090/DataCleaner-monitor/repository/DC/cluster_slave_endpoint");

    final HttpClusterManager clusterManager = new HttpClusterManager(httpClient, slaveEndpoints);

    final AnalyzerBeansConfiguration configuration = ClusterTestHelper.createConfiguration("manual_test",
            false);

    // build a job that concats names and inserts the concatenated names
    // into a file
    final AnalysisJobBuilder jobBuilder = new AnalysisJobBuilder(configuration);
    jobBuilder.setDatastore("orderdb");
    jobBuilder.addSourceColumns("CUSTOMERS.CUSTOMERNUMBER", "CUSTOMERS.CUSTOMERNAME",
            "CUSTOMERS.CONTACTFIRSTNAME", "CUSTOMERS.CONTACTLASTNAME");

    AnalyzerJobBuilder<CompletenessAnalyzer> completeness = jobBuilder.addAnalyzer(CompletenessAnalyzer.class);
    completeness.addInputColumns(jobBuilder.getSourceColumns());
    completeness.setConfiguredProperty("Conditions",
            new CompletenessAnalyzer.Condition[] { CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL });

    AnalysisJob job = jobBuilder.toAnalysisJob();
    jobBuilder.close();

    AnalysisResultFuture result = new DistributedAnalysisRunner(configuration, clusterManager).run(job);

    if (result.isErrornous()) {
        throw result.getErrors().get(0);
    }

    final List<AnalyzerResult> results = result.getResults();
    for (AnalyzerResult analyzerResult : results) {
        System.out.println("result:" + analyzerResult);
        if (analyzerResult instanceof CompletenessAnalyzerResult) {
            int invalidRowCount = ((CompletenessAnalyzerResult) analyzerResult).getInvalidRowCount();
            System.out.println("invalid records found: " + invalidRowCount);
        } else {
            System.out.println("class: " + analyzerResult.getClass().getName());
        }
    }
}

From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from  w  w  w.j a  v  a 2s. c om
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));

        HttpHost targetHost = new HttpHost("pt.3g.qq.com");
        HttpHost proxy = new HttpHost("133.13.162.149", 8080);

        BasicClientCookie netscapeCookie = null;

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // httpclient.getCookieStore().addCookie(netscapeCookie);
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        HttpGet httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("via proxy: " + proxy);
        System.out.println("to target: " + targetHost);

        HttpResponse response = httpclient.execute(targetHost, httpget);

        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        InputStream is = entity.getContent();
        StringBuffer sb = new StringBuffer(200);
        byte data[] = new byte[65536];
        int n = 1;
        do {
            n = is.read(data);
            if (n > 0) {
                sb.append(new String(data));
            }
        } while (n > 0);

        // System.out.println(sb);
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");
        Header[] headerlist = response.getAllHeaders();
        for (int i = 0; i < headerlist.length; i++) {
            Header header = headerlist[i];
            if (header.getName().equals("Set-Cookie")) {
                String setCookie = header.getValue();
                String cookies[] = setCookie.split(";");
                for (int j = 0; j < cookies.length; j++) {
                    String cookie[] = cookies[j].split("=");
                    CookieManager.cookie.put(cookie[0], cookie[1]);
                }
            }
            System.out.println(header.getName() + ":" + header.getValue());
        }
        String sid = getSid(sb.toString(), "&");
        System.out.println("sid: " + sid);

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));
        String url = Constant.openUrl + "&" + sid;
        targetHost = new HttpHost(url);

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        Iterator it = CookieManager.cookie.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            netscapeCookie = new BasicClientCookie((String) (key), (String) (value));
            netscapeCookie.setVersion(0);
            netscapeCookie.setDomain(".qq.com");
            netscapeCookie.setPath("/");
            // httpclient.getCookieStore().addCookie(netscapeCookie);
        }

        response = httpclient.execute(targetHost, httpget);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.emc.cto.ridagent.rid.test.TestScript.java

public static void main(String args[]) throws SAXException, ParserConfigurationException, URISyntaxException,
        ClientProtocolException, IOException {
    String xmlData = "  <iodef-rid:RID lang=\"en\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:iodef-rid=\"urn:ietf:params:xml:ns:iodef-rid-2.0\" xmlns:iodef=\"urn:ietf:params:xml:ns:iodef-1.42\" xsi:schemaLocation=\"urn:ietf:params:xml:ns:iodef-rid-2.0 iodef-rid-2.0.xsd\">";
    xmlData = xmlData + "<iodef-rid:RIDPolicy MsgType=\"Report\" MsgDestination=\"RIDSystem\">";
    xmlData = xmlData + "<iodef-rid:PolicyRegion region=\"IntraConsortium\"/>";
    xmlData = xmlData + " <iodef:Node>";
    xmlData = xmlData + "   <iodef:NodeName>192.168.1.1</iodef:NodeName>";
    xmlData = xmlData + " </iodef:Node>";
    xmlData = xmlData + "<iodef-rid:TrafficType type=\"Network\"/>";
    xmlData = xmlData + "</iodef-rid:RIDPolicy>";
    xmlData = xmlData + "</iodef-rid:RID>";
    String id = TestScript.httpSend(xmlData, "https://ridtest.emc.com:4590/");
    HttpGet httpget = new HttpGet("http://localhost:1280/federation/RID/" + id + "/report.xml");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    Credentials defaultcreds = new UsernamePasswordCredentials("Administrator", "secret");
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            defaultcreds);/* w  w w.  j a  v  a 2  s. co m*/
    httpget.setHeader("User-Agent", "EMC RID System");

    HttpResponse response = httpclient.execute(httpget);
    if (response.getEntity() != null) {

        int code = response.getStatusLine().getStatusCode();
        if (code == 404) {
            System.out.println("Error has occured! Document not found in the xDB");

        } else if (code == 200) {
            System.out.println("Document Successfully saved in the database");

        } else {
            System.out.println("Error could not be determined");
        }
    }
}

From source file:com.dlmu.heipacker.crawler.client.ClientKerberosAuthentication.java

public static void main(String[] args) throws Exception {

    System.setProperty("java.security.auth.login.config", "login.conf");
    System.setProperty("java.security.krb5.conf", "krb5.conf");
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from  ww w .java  2  s . co  m*/
        httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());

        Credentials use_jaas_creds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), use_jaas_creds);

        HttpUriRequest request = new HttpGet("http://kerberoshost/");
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println("----------------------------------------");
        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }
        System.out.println("----------------------------------------");

        // This ensures the connection gets released back to the manager
        EntityUtils.consume(entity);

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:httpclient.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Create local execution context
    HttpContext localContext = new BasicHttpContext();

    HttpGet httpget = new HttpGet("http://localhost/test");

    boolean trying = true;
    while (trying) {
        System.out.println("executing request " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget, localContext);

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        // Consume response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.consumeContent();/*from   www .j a  v  a2  s . c o  m*/
        }

        int sc = response.getStatusLine().getStatusCode();

        AuthState authState = null;
        if (sc == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }

        if (authState != null) {
            System.out.println("----------------------------------------");
            AuthScope authScope = authState.getAuthScope();
            System.out.println("Please provide credentials");
            System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
            System.out.println(" Realm: " + authScope.getRealm());

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

            System.out.print("Enter username: ");
            String user = console.readLine();
            System.out.print("Enter password: ");
            String password = console.readLine();

            if (user != null && user.length() > 0) {
                Credentials creds = new UsernamePasswordCredentials(user, password);
                httpclient.getCredentialsProvider().setCredentials(authScope, creds);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.dlmu.heipacker.crawler.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//w  ww .  j a v  a 2 s. com
        // Create local execution context
        HttpContext localContext = new BasicHttpContext();

        HttpGet httpget = new HttpGet("http://localhost/test");

        boolean trying = true;
        while (trying) {
            System.out.println("executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget, localContext);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Consume response content
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);

            int sc = response.getStatusLine().getStatusCode();

            AuthState authState = null;
            HttpHost authhost = null;
            if (sc == HttpStatus.SC_UNAUTHORIZED) {
                // Target host authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            }
            if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // Proxy authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
            }

            if (authState != null) {
                System.out.println("----------------------------------------");
                AuthScheme authscheme = authState.getAuthScheme();
                System.out.println("Please provide credentials for " + authscheme.getRealm() + "@"
                        + authhost.toHostString());

                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter username: ");
                String user = console.readLine();
                System.out.print("Enter password: ");
                String password = console.readLine();

                if (user != null && user.length() > 0) {
                    Credentials creds = new UsernamePasswordCredentials(user, password);
                    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
                    trying = true;
                } else {
                    trying = false;
                }
            } else {
                trying = false;
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}