使用Java为服务帐户授权的Google Analytics OAuth2

时间:2015-11-18 22:03:51

标签: java oauth google-analytics oauth-2.0 google-oauth2

为了让我能够访问Google分析数据,我正在尝试构建一个Java程序来执行身份验证并返回一个访问令牌。因此,我可以在数据仓库工具中使用访问令牌,并对Analytics API进行HTTP调用。由于这是服务器 - 服务器模型,因此我创建了一个服务帐户。但我不确定在Google OAuth API中使用哪些类别/方法来请求访问令牌。

我是Java的新宠,我想知道如何解决这个问题。

这是我到目前为止所拥有的。

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.analytics.AnalyticsScopes;
import java.io.File;
//import java.io.IOException;

public class HelloAnalytics {

private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String KEY_FILE_LOCATION = "C:/myfile.p12";
private static final String SERVICE_ACCOUNT_EMAIL = "mysrvcaccnt@gmail.com";


public static void main(String[] args) {
 try {

     //TokenRequest access_token = execute();
     Credential credential = getAccessToken();        
      System.out.println("return value " +credential);
      System.exit(0);
    } 
 catch (Exception e)    {
      e.printStackTrace();
    }
  }

  private static Credential getAccessToken()  throws Exception {
    // Initializes an authorized analytics service object.

    // Construct a GoogleCredential object with the service account email
    // and p12 file downloaded from the developer console.
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
        .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
        .setServiceAccountScopes(AnalyticsScopes.all())
        .build();
    credential.getAccessToken();
    return credential;

    // Construct the Analytics service object.
    //  return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
    //    .setApplicationName(APPLICATION_NAME).build();
  }

}

0 个答案:

没有答案