Example usage for org.apache.http.auth AuthScope AuthScope

List of usage examples for org.apache.http.auth AuthScope AuthScope

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope AuthScope.

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

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

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {// w  w w. j  ava  2  s.  c  o  m
        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.lxf.spider.client.ClientPreemptiveBasicAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("localhost", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//w w w .ja  v a 2s .com

        // 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(target, basicAuth);

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

        HttpGet httpget = new HttpGet("/");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.lxf.spider.client.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("localhost", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//w ww.j  av a 2 s .c  om

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        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");
        authCache.put(target, digestAuth);

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

        HttpGet httpget = new HttpGet("/");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

From source file:demo.example.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("httpbin.org", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/*w w  w  .  j a v  a  2  s  .c om*/

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        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");
        authCache.put(target, digestAuth);

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

        HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

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 v a2 s  .com*/
    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);//from  ww  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.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 {//w w  w.j  a va2  s .  c o  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:httpclient.client.ClientPreemptiveBasicAuthentication.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 BASIC scheme object and stick it to the local 
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

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

    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();//  ww  w. j a v a  2 s.c o  m
        }
    }

    // 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:mai.cn.film.auth.ClientAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost targetHost = new HttpHost("www.filmaffinity.com", 80, "http");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from   www. jav  a 2 s.  c om*/

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("picarus", "8C8PPkEc"));

        // 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("http://www.filmaffinity.com/en/myvotes.php");

        System.out.println("executing request" + httpget.getRequestLine());

        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        HttpResponse response = httpclient.execute(httpget);
        String responseBody = responseHandler.handleResponse(response);
        int code = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");

        System.out.println("----------------------------------------");
        System.out.println("Status:" + code + " " + response.getStatusLine().getReasonPhrase());

        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: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();/*  www.ja va 2  s  .c  o m*/
        }
    }

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