hc-httpclient-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Cody Burleson <cody.burle...@base22.com>
Subject Newbie - need help with basic authentication
Date Thu, 14 Oct 2010 14:48:52 GMT
Team,

I am brand new to HttpClient and I am trying to authenticate with a site
through Basic HTTP Authentication. I am having no luck and am finding it
difficult to refer to the code examples because they seem to be primarily
for former versions of the library (I am using version 4.0.3.)

Could somebody throw a newbie a bone and take a quick gander at this code?
What am I doing wrong?

I use the static method in the following class to attempt to authenticate
with a site and get the response. In a servlet, I use this code to connect
to the server and then after first connection (assuming it logged in), I
redirect to the same URL. But I am still challenged with the basic http
dialog for credentials. Any ideas?

========================

package com.base22.http;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
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.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.io.StreamUtils;



/**
 * 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);


    /**
     * @param credentials
     * @return
     */
    public static String get(String url,AuthScope authScope,
UsernamePasswordCredentials credentials){

        final String METHOD = " get() ";


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

        String content = null;

        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(authScope,
credentials);
        HttpGet httpget = new HttpGet(url);


        if(LOG.isDebugEnabled()){
            LOG.debug("--" + METHOD + "> executing request" +
httpget.getRequestLine());
        }

        HttpResponse response = null;
        try {

//httpclient.setCredentialsProvider(httpclient.getCredentialsProvider());
            response = httpclient.execute(httpget);
        } catch (ClientProtocolException e) {
            LOG.error("--" + METHOD + "> ClientProtocolException caught with
httpclient.execute(httpget).");
            e.printStackTrace();
        } catch (IOException e) {
            LOG.error("--" + METHOD + "> IOException caught with
httpclient.execute(httpget).");
            e.printStackTrace();
        }

        HttpEntity entity = response.getEntity();

        if(LOG.isDebugEnabled()){
            LOG.debug("--" + METHOD + "> response.getStatusLine(): " +
response.getStatusLine());
        }

        if(LOG.isDebugEnabled()){
            LOG.debug("--" + METHOD + "> Response content length: " +
entity.getContentLength());
        }

        if (entity != null) {

            if(LOG.isDebugEnabled()){
                LOG.debug("--" + METHOD + "> Got entity from
HttpResponse.");
            }
            // entity.consumeContent();
            // The name of this method is misnomer. It will be renamed to
#finish() in the next major release.
            // This method is called to indicate that the content of this
entity is no longer required.
            // All entity implementations are expected to release all
allocated resources as a result of this method invocation.
            // Content streaming entities are also expected to dispose of
the remaining content, if any.
            // Wrapping entities should delegate this call to the wrapped
entity.
            // This method is of particular importance for entities being
received from a connection.
            // The entity needs to be consumed completely in order to re-use
the connection with keep-alive.
            try {


                    entity.consumeContent();

                    //content = EntityUtils.toString(entity);
                    //InputStream is = entity.getContent();
                    //content = StreamUtils.convertToString(is);
                    //content = EntityUtils.toString(response.getEntity());

            } catch (IOException e) {
                LOG.warn("--" + METHOD + "> IOException caught with
entity.consumeContent().");
                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();

        return content;

    }

}


==============

AND IN THE SERVLET THAT USES THE ABOVE CODE:

    /**
     * @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

        if(LOG.isDebugEnabled()){
            LOG.debug(">> doGet()");
        }
        PrintWriter out = response.getWriter();

        AuthScope authScope = new AuthScope("dev.mojo.com",80,"dev.mojo.com
");

        UsernamePasswordCredentials credentials = new
UsernamePasswordCredentials("admin","adminPass");
        String result = BasicAuthenticator.get("http://dev.mojo.com/",
authScope, credentials);

        response.sendRedirect("http://dev.mojo.com/");
        out.write(result);
        out.flush();
        out.close();

    }

-- 
Cody Burleson

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message