Accessing Google Analytics Data usnig the api KEY (without user interaction to authenticate)

8,040 views
Skip to first unread message

Goss Development

unread,
May 25, 2012, 6:26:20 AM5/25/12
to google-analytics...@googlegroups.com
Can someone tell me how to access Google Analytics data from a Java program (using java-api-client or own java code)  witghout having user interaction to "Allow" access tp data.
 
I have tried the following with no luck:
 

 JsonHttpRequestInitializer initializer = new GoogleKeyInitializer("AIzaSyDkFLpg3BcceObNlpDl2odCLYElxj38atU");
 Analytics ana = Analytics.builder(new NetHttpTransport(), JSON_FACTORY).setApplicationName("My App1").setJsonHttpRequestInitializer(initializer).build();

It looks like you need to Login too. I can't figure out how to do it in the javaclient api

Also tried the following code with no luck:

 

         DefaultHttpClient client = new DefaultHttpClient();
        CookieStore store = new BasicCookieStore();
        client.setCookieStore(store);
        HttpPost method = new HttpPost("https://www.google.com/accounts/ClientLogin");
        method.setHeader("Content-Type", "application/x-www-form-urlencoded");
        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(4);
        postParams.add(new BasicNameValuePair("accountType", "GOOGLE"));
        postParams.add(new BasicNameValuePair("Email", "myac...@gmail.com"));
        postParams.add(new BasicNameValuePair("Passwd", "gossdevteam"));
        postParams.add(new BasicNameValuePair("service", "analytics"));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams);

        method.setEntity(formEntity);
        org.apache.http.HttpResponse responseTmp = client.execute(method);
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        responseTmp.getEntity().writeTo(outstream);
        byte [] responseBody = outstream.toByteArray();
        String headers = new String(responseBody);
        System.out.println("Response Headers: " + headers);
        String auth = headers.substring(headers.indexOf("Auth=") + 5);
        System.out.println("Auth: " + auth);
       
        org.apache.http.impl.client.DefaultHttpClient OAuthClient = new DefaultHttpClient();
        CookieStore OAuthCookieStore = new BasicCookieStore();
        ResponseHandler<byte[]> handlerOAuth = new ResponseHandler<byte[]>() {

            public byte[] handleResponse(org.apache.http.HttpResponse response) throws IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }

            }

        };

        OAuthClient.setRedirectHandler(new DefaultRedirectHandler() {
                public boolean isRedirected(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response)  {
                    boolean isRedirect=false;
                    if (!isRedirect) {
                        int responseCode = response.getStatusLine().getStatusCode();
                        if (responseCode == 301 || responseCode == 302) {
                            return true;
                        }
                    }
                    return false;
                }
            });
        OAuthClient.setCookieStore(OAuthCookieStore);

        String CLIENT_ID = "xxxx.apps.googleusercontent.com";
        HttpPost OAuthPost = new HttpPost("https://accounts.google.com/o/oauth2/auth");
   
      List<NameValuePair> parOAuth = new ArrayList<NameValuePair>(6);
      parOAuth.add(new BasicNameValuePair("client_id", CLIENT_ID));
      parOAuth.add(new BasicNameValuePair("redirect_uri", "https://oauth2-login-demo.appspot.com/code"));
      parOAuth.add(new BasicNameValuePair("response_type", "code"));
      parOAuth.add(new BasicNameValuePair("scope", "https://www.googleapis.com/auth/analytics.readonly"));
      OAuthPost.setEntity(new UrlEncodedFormEntity(parOAuth));
       
        byte[] OAuthResponse = OAuthClient.execute(OAuthPost, handlerOAuth);

 

 

 

 

Pete

unread,
May 25, 2012, 12:44:40 PM5/25/12
to google-analytics...@googlegroups.com
APIs for the Google Analytics service require authorized calls. So it is not possible to make calls without first authorizing access. 
What you're basically asking for is "how do I access a user's account without their permission?". This is not possible for Analytics data. There are other Google APIs that do not access user data, so authentication and authorization is not required in those cases and the API key is sufficient, but this is not true for Google Analytics APIs.

If you "login" with your own account credentials then you will have access to your Google Analytics data data. If you want to access another user's Google Analytics data then you will need to obtain authorization from the user to 'allow' your program to access their data...and OAuth 2.0 is the recommended auth mechanism to do this. 

If you stil want to proceed you should first check out the following resources:
Google Accounts Authentication and Authorization to learn how to gain authorized access

Google APIs Console Help to learn about keys, OAuth and how to register your application and obtain a Client ID and Client Secret

and then try the Hello Analytics API tutorial to get started

John Lancaster

unread,
May 26, 2012, 10:50:55 AM5/26/12
to google-analytics...@googlegroups.com
You'll want to explore offline access. Follow this post http://stackoverflow.com/questions/9366380/service-account-google-analytics-oauth-accesstype-offline-c-sharp. You'll basically simulate what you want by requesting offline access and getting a refresh token every hour.

Jeya Prakash

unread,
Feb 21, 2013, 4:13:29 AM2/21/13
to google-analytics...@googlegroups.com
i want to do it in java..

Eric Nguyen

unread,
Feb 21, 2013, 5:02:38 AM2/21/13
to google-analytics...@googlegroups.com
Hi Goss,

It's possible to achieve what you want using ClientLogin authentication method as opposed to OAuth 2.0 or OAuth 1.0 (this method will stop working in 2015).

Regarding the implementation of ClientLogin for Java, I'm sure someone on stackoverflow.com would be glad to help.

Good luck :)

Jeya Prakash

unread,
Feb 23, 2013, 9:46:41 AM2/23/13
to google-analytics...@googlegroups.com
Hi eric i got ClientLogin but i dont know how to call it in a HelloAnlayticApi.java. Can you help me. pleaseeee...

Eric Nguyen

unread,
Feb 25, 2013, 3:48:51 AM2/25/13
to google-analytics...@googlegroups.com
I've discovered that Google gives very minimal quota to apps/ websites using ClientLogin protocol. I was about to use it for 2 days and everything just stopped. There is no documentation explaining clearly how much quota is given ClientLogin either.

So, the solution is to use OAuth 2.0 + refresh token (so you would only have to authorized the app once and for all). How to achieve such goal is complex and I'm still figuring out myself.

Good luck ;)

Jeya Prakash

unread,
Feb 26, 2013, 4:20:45 AM2/26/13
to google-analytics...@googlegroups.com

Jeya Prakash

unread,
Feb 26, 2013, 4:23:20 AM2/26/13
to google-analytics...@googlegroups.com


On Tuesday, 26 February 2013 14:50:45 UTC+5:30, Jeya Prakash wrote:
What about Management api?

i execute successful but got null answers 

Jeya Prakash

unread,
Feb 26, 2013, 4:27:57 AM2/26/13
to google-analytics...@googlegroups.com
i am doing a project to fetch data from google analytics automatically.so automatic login is most recommended.if u have any other idea kindly share with me

Jeya Prakash

unread,
Feb 26, 2013, 4:30:04 AM2/26/13
to google-analytics...@googlegroups.com
by using clientLogin i got authtoken but after that i stuck to proceed.

Eric Nguyen

unread,
Feb 26, 2013, 4:50:21 AM2/26/13
to google-analytics...@googlegroups.com
Yes, your goal is exactly the same mine.

The point is you won't be able to very far with ClientLogin so I strongly suggest that you start digging into OAuth 2.0 now.

If I understand what you mean by "automatic login" correctly, "refresh token" is what you need, google it out ;)

Good luck :)

Nick

unread,
Feb 26, 2013, 12:54:36 PM2/26/13
to google-analytics...@googlegroups.com
+1 Google it out

Google Analytics requires authorization, so there needs to be some user interaction at least once.

-Nick
Reply all
Reply to author
Forward
0 new messages