You are viewing a plain text version of this content. The canonical link for it is here.
Posted to httpclient-users@hc.apache.org by Cody Burleson <co...@base22.com> on 2010/10/31 21:29:44 UTC

Help! Trouble Getting Cookies

Hey friends, I'm stuck. As if you have nothing better to do, can any fine
guru tell me why in the heck my attempt to list cookies is always printing
"None"?

See, in the class below, the section just below the stanza:

// **************************************************************
// LIST COOKIES
// **************************************************************


--------------------- CLASS >>

package com.base22.http;

import java.io.IOException;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.base22.constants.SYS;

/**
 * Authenticates through Basic HTTP Authentication.
 *
 * <p>
 * Depends on the Apache HttpClient and HttpCore libraries as well as Log4J.
 * </p>
 *
 * @author Cody Burleson
 *
 */
public class BasicAuthenticator {

    static Logger LOG = Logger.getLogger(BasicAuthenticator.class);

    private AuthScope authScope;
    private UsernamePasswordCredentials credentials;


    public BasicAuthenticator(AuthScope authScope,
            UsernamePasswordCredentials credentials){
        this.authScope = authScope;
        this.credentials = credentials;
    }

    /**
     * @param credentials
     * @return
     */
    public String get(String url) {

        final String METHOD = " get() ";

        String content = null;

        if (LOG.isTraceEnabled()) {
            LOG.trace(">>" + METHOD);
        }







        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(this.authScope,
this.credentials);

        // Some web servers will reject a request from an unknown user agent
        // untested..
        httpclient.getParams().setParameter("User-Agent","Mozilla/5.0
(Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208
Firefox/3.0.1");



        /*
        List authPrefs = new ArrayList(2);
        authPrefs.add(AuthPolicy.BASIC);
        authPrefs.add(AuthPolicy.DIGEST);
        httpclient.getParams().setParameter(AuthPolicy.BASIC, authPrefs);
        */


        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 PreemptiveAuthInterceptor(),
0);

        HttpHost targetHost = new HttpHost("dev.base22.com", 80, "http");
        HttpGet httpget = new HttpGet("/");


        // *********** DEBUG
        LOG.debug("*************** REQ HEADERS\n");
        Header[] headerz = httpget.getAllHeaders();
        for (int j = 0; j < headerz.length; j++) {
            Header header = headerz[j];
            LOG.debug("--" + METHOD + header.getName() + " = " +
header.getValue());
        }
        // ********** END DEBUG


        // Examine the response status
        System.out.println("executing request: " +
httpget.getRequestLine());
        System.out.println("to target: " + targetHost);


        try {

            for (int i = 0; i < 3; i++) {

                // RIGHT HERE IS WHERE THE CLIENT CAN HANG FOR A LONG TIME
IF THE SERVER
                // IS NOT RESPONDING. SOME KIND OF TIMEOUT MECHANISM MIGHT
BE GOOD

                HttpResponse response = httpclient.execute(targetHost,
httpget, localcontext);
                HttpEntity entity = response.getEntity();


//System.out.println("----------------------------------------");
                if(LOG.isDebugEnabled()){
                    LOG.debug("-- get() > response.getStatusLine: " +
response.getStatusLine());
                }

                // DEBUG ONLY
-------------------------------------------------------------------------------
                if(LOG.isDebugEnabled()){
                    Header[] headers = response.getAllHeaders();
                    StringBuffer sb = new StringBuffer();
                    sb.append("-- get() > All Headers [").append(SYS.NL);
                    for (int j = 0; j < headers.length; j++) {
                        Header header = headers[j];
                        sb.append("\t").append(header.getName()).append(" =
").append(header.getValue());
                        sb.append(SYS.NL);
                    }
                    sb.append("]").append(SYS.NL);
                    LOG.debug(sb.toString());
                }
                // END DEBUG ONLY
----------------------------------------------------------------------------

                if (entity != null) {
                    LOG.debug("--" + METHOD + "Response content length: " +
entity.getContentLength());

                    // LOG.debug("ResponseBODY: " +
EntityUtils.toString(entity));
                    //entity.consumeContent();

                    content = EntityUtils.toString(entity);

                    //DefaultHttpClient httpClient = (DefaultHttpClient)
webClient.getHttpClient();

                    //
**************************************************************
                    // LIST COOKIES
                    //
**************************************************************
                    List<Cookie> cookies =
httpclient.getCookieStore().getCookies();

                    if(LOG.isDebugEnabled()){
                        StringBuffer sb = new StringBuffer();
                        sb.append("-- get() > Cookies [").append(SYS.NL);
                        if (cookies.isEmpty()) {
                            sb.append("None").append(SYS.NL);
                          } else {
                            for (int x = 0; x < cookies.size(); x++) {
                              sb.append("\t").append("- " +
cookies.get(x).toString());
                              sb.append(SYS.NL);
                            }
                          }
                        sb.append("]").append(SYS.NL);
                        LOG.debug(sb.toString());
                    }

                }

            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources

        httpclient.getConnectionManager().shutdown();

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

        //if(LOG.isDebugEnabled()){
            //LOG.debug("<<" + METHOD + "returning: " + content);
        //}

        return content;

    }



}


-- 
Cody Burleson

Re: Help! Trouble Getting Cookies

Posted by Oleg Kalnichevski <ol...@apache.org>.
On Sun, 2010-10-31 at 16:29 -0400, Cody Burleson wrote:
> Hey friends, I'm stuck. As if you have nothing better to do, can any fine
> guru tell me why in the heck my attempt to list cookies is always printing
> "None"?
> 

You can see whether or not the target server sends any cookies back and
whether or not they get rejected by HttpClient by activating the wire /
context logging.

http://hc.apache.org/httpcomponents-client-ga/logging.html

Oleg 


---------------------------------------------------------------------
To unsubscribe, e-mail: httpclient-users-unsubscribe@hc.apache.org
For additional commands, e-mail: httpclient-users-help@hc.apache.org