使用不同凭据访问 Google Analytics 报告数据时出现空指针异常

Null Pointer Exception when accessing Google Analytics report data using different credentials

我正在关注 tutorial 通过使用 Google 开发人员控制台执行简单的 GA 查询来访问 GA 帐户报告数据。 我按照教程中提到的所有步骤进行操作,代码运行良好。

我已经包含了下面的代码。

public class GoogleAnalyticsAccess {

    private static final String APPLICATION_NAME = "GAAccess/1.0";
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".store/analytics_sample");
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static FileDataStoreFactory dataStoreFactory;
    private static HttpTransport httpTransport;

    public static Credential authorizeUser() throws IOException {

        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(
                GoogleAnalyticsAccess.class.getResourceAsStream("/client_secrets.json")));
        if (clientSecrets.getDetails().getClientId().startsWith("Enter") ||
            clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/?api=analytics " +
                               "into Dashboard/src/main/resources/client_secrets.json");
            System.exit(1);
        }
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
                                                                                   clientSecrets, Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY))
                .setDataStoreFactory(dataStoreFactory).build();

        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    public static Analytics getAnalyticsServiceObject(Credential credential){

        return new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                                                                             .build();
    }

    public static String getGAAccountId(Analytics analytics) throws IOException {

        String accountId =null;

        Accounts accounts = analytics.management().accounts().list().execute();
        List<Account> accountsList = accounts.getItems();

        if(accountsList.isEmpty()){
            System.err.println("No accounts found");
        }
        else{

            for(int i=0; i<accountsList.size();i++){
                if(accountsList.get(i).getName().equals("XXXX")){
                    accountId = accountsList.get(i).getId();
                    break;
                }
            }
        }

        return accountId;
    }

    public static String getGAWebPropertyId(Analytics analytics,String accountId) throws IOException {

        String webPropertyId = null;

        Webproperties webProperties = null;

        webProperties = analytics.management().webproperties().list(accountId).execute();
        List<Webproperty> webPropertiesList = webProperties.getItems();

        if (webPropertiesList.isEmpty()) {
            System.err.println("No Web Properties found");
        } else {

            for (int i=0; i<webPropertiesList.size();i++){
                if(webPropertiesList.get(i).getName().equals("XXXX")){
                    webPropertyId = webPropertiesList.get(i).getId();
                }
            }
        }

        return webPropertyId;
    }

    public static String getGAViewId(Analytics analytics, String accountId, String webPropertyId) throws IOException {

        String viewId = null;

        Profiles views = analytics.management().profiles().list(accountId, webPropertyId).execute();
        List<Profile> viewsList = views.getItems();

        if (viewsList.isEmpty()) {
            System.err.println("No profiles found");
        } else {
            for(int i=0; i<viewsList.size();i++){
                if(viewsList.get(i).getName().equals("XXXX")){
                    viewId = viewsList.get(i).getId();
                }
            }
        }

        return viewId;

    }

    public static List<GoogleAnalyticsData> executeGAQuery(Analytics analytics, String viewId, String dimension) throws IOException {

        List<GoogleAnalyticsData> dataList = new ArrayList<GoogleAnalyticsData>();

        if (viewId == null) {
            System.err.println("No profiles found.");
        } else {
            GaData gaData = analytics.data().ga().get("ga:" + viewId, "2015-02-13", "2015-02-27", "ga:users")
                                     .setDimensions("ga:" + dimension)
                                     .setMaxResults(200).execute();

            if (gaData.getRows() == null || gaData.getRows().isEmpty()) {
                System.out.println("No results Found.");
            } else {
                GoogleAnalyticsData data;
                for (List<String> row : gaData.getRows()) {
                    data = new GoogleAnalyticsData();
                    data.setName(row.get(0));
                    data.setValue(Integer.parseInt(row.get(1)));

                    dataList.add(data);
                }
            }
        }

        return dataList;
    }

    public static void main(String[] args) throws GeneralSecurityException, IOException {

        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

        Credential credential = authorizeUser();
        Analytics analytics = getAnalyticsServiceObject(credential);
        String accountId = getGAAccountId(analytics);
        String webPropertyId = getGAWebPropertyId(analytics,accountId);
        String viewId = getGAViewId(analytics,accountId,webPropertyId);

        List<GoogleAnalyticsData> continentDataList = executeGAQuery(analytics, viewId, "continent");
        List<GoogleAnalyticsData> countryDataList = executeGAQuery(analytics, viewId, "country");

        for(int i =0; i <continentDataList.size();i++){
            System.out.println(continentDataList.get(i).getName() + " " + continentDataList.get(i).getValue());

        }

        for(int i=0; i< countryDataList.size();i++){
            System.out.println(countryDataList.get(i).getName() + " " + countryDataList.get(i).getValue());
        }

    }

}

当我通过提供另一个用户的凭据(客户端密码和 ID)访问相同的 GA 帐户报告数据时,我收到了一个错误,该用户也可以共享该报告数据的访问权限。 我可以使用其他用户凭据成功访问报告数据如果我已经 运行 java 应用程序首先使用我的凭据。但是,如果我 运行 应用程序首先使用其他用户凭据,则会出现以下错误。

堆栈跟踪如下所示。

Exception in thread "main" java.lang.NullPointerException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:92)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at org.dashboard.access.data.GoogleAnalyticsAccess.getGAAccountId(GoogleAnalyticsAccess.java:266)
at org.dashboard.access.data.GoogleAnalyticsAccess.main(GoogleAnalyticsAccess.java:364)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

具体的异常发生在方法getGAAccountId的下面一行。

Accounts accounts = analytics.management().accounts().list().execute();

这个问题有什么解决方法吗?

如果您的 client_secrets.json 配置正确,您只需删除文件。store/analytics_sample 并再次 运行 它。