We all started somewhere! Share your experience on the Get Advice: Let's Get Started Sweepstakes thread and be entered to win a $100 credit on your Constant Contact account.

Java sample code


Java sample code

We are trying to use the APIs using HttpClient in java. We can't seem to connect due to a :Unknown Host Exception

We we would really  appreciate some java code sample since we couldn't find it in the web site.

Here is a part of the code :


            HttpHost targetHost = new HttpHost("api.constantcontact.com/ws/customers/"our username"/campaigns","https");


            DefaultHttpClient httpclient = new DefaultHttpClient();


            new AuthScope(targetHost.getHostName(), targetHost.getPort()),

            new UsernamePasswordCredentials("apikey%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("/");

            HttpResponse response = null;

        try {


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



We avoided putting real password and api keys due to security reasons.

Looking forward to a quick response.

Best regards

Gaston Ashby

Occasional Participant

Hi Gaston. I am trying to get your code running in my environment using my own api keys, etc. Could you please post the Java imports that you are using? There are too many possible places to obtain things like HttpClient and DefaultHttpClient for me to guess which you are using. I'd like to get my environment looking as much like yours as possible.


Matt Laudato

Contstant Contact

Matthew D. Laudato

Constant Contact

Occasional Participant

OK, I have some working code. Couple of points:

1. I used httpcomponents-client-4.1 from Apache (http://hc.apache.org/downloads.cgi, and select the 4.1 GA zip).

2. I made some small changes to how the HttpHost and HttpGet objects are constructed:

HttpHost targetHost = new HttpHost("api.constantcontact.com", -1, "https");


HttpGet httpget = new HttpGet("/ws/customers/USERNAME/campaigns");

(Note, this uses the 3 param constructor for HttpHost - there is no 2 paramter String,String version available in the httpcomponents library that I used).

Works correctly.

Please repost when you have a chance to try this - and hope this helps.





Matthew D. Laudato

Constant Contact

Developer Portal

View API documentation, code samples, get your API key.

Visit Page