How to connect to Google Analytics Data API in AIR

I had a bit of trouble doing just this a while ago, ended up trying many different ways and finally a reader of this blog, Nakamachi, gave me the solution. Because I think many of you are trying to connect to Google Analytics Data API ( or any Google APIs for that matters) I will give you here my solution. My solution only works in AIR; I don’t know why, but as soon as I put it on the web, it stops working. I have found a solution for that problem too but I will keep it for another post.
Here is how you can connect to GData:

import org.httpclient.HttpClient;
import com.adobe.net.URI;
import org.httpclient.events.HttpResponseEvent;
import org.httpclient.events.HttpRequestEvent;
import org.httpclient.HttpRequest;
import org.httpclient.http.Get;
import org.httpclient.events.HttpDataEvent;
 
var _firstBuffer:String = "";
var _secondBuffer:String = "";
 
//this first connection will get the authorization token by sending the user name and password for Google Analytics
function submitForm(email:String, password:String):void {
  var client:HttpClient = new HttpClient();
  var uri:URI = new URI("https://www.google.com/accounts/ClientLogin");
  var variables:Array = [{name:"accountType", value:"GOOGLE"}, {name:"Email", value: email}, {name:"Passwd", value: password}, {name:"service", value: "analytics"}, {name:"source", value: "your-application-identifier"}];
  client.listener.onData = _onFirstData;
  client.listener.onComplete = _onLoaderComplete;
  client.postFormData(uri, variables);
}
 
function _onFirstData(event:HttpDataEvent):void {
  _firstBuffer += event.readUTFBytes();
}
 
//this second connection will request information to GData
//in this case account info for Google Analytics by
//putting the auth token in the header of the request
function _onLoaderComplete(event:HttpResponseEvent):void {
  var tempArray:Array = _firstBuffer.split("Auth=");
 var  _authToken:String = String(tempArray[1]);
 
  var client:HttpClient = new HttpClient();
  var uri:URI = new URI("https://www.google.com/analytics/feeds/accounts/default");
  var request:HttpRequest = new Get();
  request.addHeader("Authorization", "GoogleLogin auth=" + _authToken);
 
  client.listener.onData = function(event:HttpDataEvent):void {
    _secondBuffer += event.readUTFBytes();
  }
  client.listener.onComplete = _onSecondLoaderComplete;
  client.request(uri, request);
}
 
function _onSecondLoaderComplete(event:HttpResponseEvent):void {
  trace (_secondBuffer);
}

As you can see in order to circumvent the Authorization header restriction I am using the as3httpclientlib library which requires the as3corelib and as3crypto libraries to compile. Using the same principle you should be able to connect to Google APIs from your AIR application.

, , , , , , , ,

  1. #1 by Davide - May 27th, 2009 at 03:34

    Hi! I have the same problem but I need to use browser for my application… could you please give me some hints to solve?

  2. #2 by Tracy Spratt - June 14th, 2009 at 19:39

    Ok, great, thanks, ignore my question from the other page.

  3. #3 by Nick Green - July 13th, 2009 at 13:31

    I think I’m in love. Thank you so much. I’m not exactly sure how requiring the developer to utilize three third-party class libraries makes anything more secure, but I’m much indebted to you for figuring this one out and sharing your success!!!

    Thanks again!

  4. #4 by Nick Green - July 22nd, 2009 at 13:34

    I got pulled onto another project just after implementing this. A couple other developers and I have worked with this, but have had issues casting the result as correctly parsable XML.

    I’ve checked a few HttpClient documentation and tutorial sites, but haven’t been able to find the root of the issue.

    Have you had any similar problems? Any help would be greatly appreciated.

    My code attached below:

    //Namespace Complicator Killer
    var dimNSPat:RegExp = /dxp\:/g;
    var nsFixed:String = _thirdBuffer.replace(dimNSPat, “dxp”);
    dimNSPat = /\r|\n/;
    nsFixed = nsFixed.replace(dimNSPat, ” “);
    //Define XML
    reportXML.ignoreWhitespace = true;
    reportXML.prettyPrint = true;
    reportXML.prettyIndent = true;
    reportXML = XML(nsFixed);
    //Display XML
    nodeTxt.text = nsReportXML.entry;
    nodeTxt.text += “DONE”;

  5. #5 by zedia.net - July 22nd, 2009 at 14:11

    @Nick Green
    I actually stoped working on this as soon as I got the Flash/online version to work, so I haven’t parsed the XML yet. One thing I noticed though that there might be an added character that you don’t need before the XML start so you might want to check it out.

  6. #6 by Nick Green - July 30th, 2009 at 12:50

    I figured out the issue. In the AS3 implementation of HTTPClient (Rather than the MXML implementation) there isn’t a parameter defining the type of data returned. The result is an object, rather than an E4X navigable XML. It can be converted using the code below:

    reportXML = new XML(_thirdBuffer);
    dataXML = reportXML as XML; //This second casting is the key step

    var dxpNS:Namespace = dataXML.namespace(“dxp”);

    var dXMLList:XMLList = dataXML..dxpNS::dimension.@value;
    var mXMLList:XMLList = dataXML..dxpNS::metric.@value;

  7. #7 by skwasha - September 25th, 2009 at 01:21

    Had to make 2 slight mods to get this to work.

    1) in _onLoaderComplete, stripped trailing linefeed from auth token that was causing errors.
    var _authToken:String = String(tempArray[1]).replace(‘\n’,”);

    2) also in _onLoaderComplete, added an additional header for Data API access.
    request.addHeader(“GData-Version”, “3.0″);

  8. #8 by chrillo - March 4th, 2010 at 06:36

    HI
    I just want to say thank you so much. I spent an entire day trying to work around that issue and thanks to your post it took me just 10 minutes to get it running in the end. THANK YOU!

  9. #9 by danel kirch - June 30th, 2010 at 18:35

    Is it possible to authenicate on Joomla CMS with this ?

    Ive been sitting here hours now and no success, so now i wonder if its even possible.

    anykind of example that would help out ?

  10. #10 by leef - July 30th, 2010 at 13:09

    Thanks for this resource, bummer that connecting to HTTPS services are as complex as they are in AS3, I was hoping for a higher level API from Adobe but am very appreciative of what you’ve built on hurlant’s TLS classes!

  11. #11 by leef - July 30th, 2010 at 13:56

    I replaced hurlant’s TLSSocket with SecureSocket & removed the startTLS line, and your package seems to work great with SecureSocket.

  12. #12 by Neil - September 16th, 2010 at 15:16

    Thank you this is a great example. I am trying to use this technique to get data from google trends. I get the whole page back as the result but if you are logged in you can download a CSV file with the results.

    Have you any ideas on how to get google trends data or that CSV file?

    Thanks again.

(will not be published)
Subscribe to comments feed