Example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext

List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext

Introduction

In this page you can find the example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext.

Prototype

public BasicHttpContext() 

Source Link

Usage

From source file:yangqi.hc.HttpContextTest.java

/**
 * @param args//from  ww w.j a v  a2 s . c om
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    // TODO Auto-generated method stub
    HttpClient httpclient = new DefaultHttpClient();

    HttpContext context = new BasicHttpContext();

    // Prepare a request object
    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute the request
    HttpResponse response = httpclient.execute(httpget, context);

    showAttr(ExecutionContext.HTTP_CONNECTION, context);
    showAttr(ExecutionContext.HTTP_PROXY_HOST, context);
    showAttr(ExecutionContext.HTTP_REQ_SENT, context);
    showAttr(ExecutionContext.HTTP_RESPONSE, context);
    showAttr(ExecutionContext.HTTP_REQUEST, context);
    showAttr(ExecutionContext.HTTP_TARGET_HOST, context);

}

From source file:com.mama100.android.member.http.ClientCustomContext.java

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

    HttpClient httpclient = new DefaultHttpClient();

    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Create local HTTP context
    HttpContext localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet("http://www.weibo.com/");

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

    // Pass local context as a parameter
    HttpResponse response = httpclient.execute(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());
    }//from   ww  w  . j ava 2 s  .  c om
    List<Cookie> cookies = cookieStore.getCookies();
    for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Local cookie: " + cookies.get(i));
    }

    // Consume response content
    if (entity != null) {
        entity.consumeContent();
    }

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

    // 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.hilatest.httpclient.apacheexample.ClientCustomContext.java

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

    HttpClient httpclient = new DefaultHttpClient();

    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Create local HTTP context
    HttpContext localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet("http://www.google.com/");

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

    // Pass local context as a parameter
    HttpResponse response = httpclient.execute(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());
    }/*  www.  j a  va2s .com*/
    List<Cookie> cookies = cookieStore.getCookies();
    for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Local cookie: " + cookies.get(i));
    }

    // Consume response content
    if (entity != null) {
        entity.consumeContent();
    }

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

    // 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.music.tools.SongDBDownloader.java

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

    //        HttpHost proxy = new HttpHost("localhost", 8888);
    //        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpContext ctx = new BasicHttpContext();

    HttpUriRequest req = new HttpGet(
            "http://www.hooktheory.com/analysis/view/the-beatles/i-want-to-hold-your-hand");
    client.execute(req, ctx);//from w w  w .  j a v  a 2s. c om
    req.abort();

    List<String> urls = getSongUrls(
            "http://www.hooktheory.com/analysis/browseSearch?sQuery=&sOrderBy=views&nResultsPerPage=525&nPage=1",
            client, ctx);
    List<List<? extends NameValuePair>> paramsList = new ArrayList<>(urls.size());
    for (String songUrl : urls) {
        paramsList.addAll(getSongParams(songUrl, client, ctx));
    }
    int i = 0;
    for (List<? extends NameValuePair> params : paramsList) {

        HttpPost request = new HttpPost("http://www.hooktheory.com/songs/getXML");

        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        request.setHeader("Accept-Encoding", "gzip, deflate");
        request.setHeader("Accept-Language", "en,en-us;q=0.7,bg;q=0.3");
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setHeader("Origin", "http://www.hooktheory.com");
        request.setHeader("Referer",
                URLEncoder.encode("http://www.hooktheory.com/swf/DNALive Version 1.0.131.swf", "utf-8"));

        HttpEntity entity = new UrlEncodedFormEntity(params);
        request.setEntity(entity);

        try {
            HttpResponse response = client.execute(request, ctx);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream is = response.getEntity().getContent();
                String xml = CharStreams.toString(new InputStreamReader(is));
                is.close();
                Files.write(xml, new File("c:/tmp/musicdb/" + i + ".xml"), Charset.forName("utf-8"));
            } else {
                System.out.println(response.getStatusLine());
                System.out.println(params);
            }
            i++;
            request.abort();
        } catch (Exception ex) {
            System.out.println(params);
            ex.printStackTrace();
        }
    }
}

From source file:com.mtea.macrotea_httpclient_study.ClientCustomContext.java

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

    HttpClient httpclient = new DefaultHttpClient();
    try {/*from   www. ja va  2  s. c  om*/
        // CookieStore 
        CookieStore cookieStore = new BasicCookieStore();

        // HttpContext 
        HttpContext localContext = new BasicHttpContext();

        //HttpContextCookieStore
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpGet httpget = new HttpGet("http://www.google.com/");

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

        // ?
        HttpResponse response = httpclient.execute(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());
        }

        //???cookie
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        //
        EntityUtils.consume(entity);

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

    } finally {
        //??httpclient???
        httpclient.getConnectionManager().shutdown();
    }
}

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

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

    HttpClient httpclient = new DefaultHttpClient();
    try {//from w w w .  j a  v  a2s  .  co m
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();

        // Create local HTTP context
        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpGet httpget = new HttpGet("http://www.google.com/");

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

        // Pass local context as a parameter
        HttpResponse response = httpclient.execute(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());
        }
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        // Consume response content
        EntityUtils.consume(entity);

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

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();/*from   www .j  a v  a  2s  .co  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: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();// w w  w.j  av  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();
}