1

我正在尝试使用 java google-api 访问 Adsense Management API。但是,我在 oauth2 身份验证方面遇到了麻烦。根据文档,以下代码应该足够了:

public static GoogleCredential getCredential() 
   throws GeneralSecurityException, IOException {
    File file = new File("key.p12");
    return new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(SERVICE_ACCOUNT_ID)
            .setServiceAccountScopes(AdSenseScopes.ADSENSE)
            .setServiceAccountPrivateKeyFromP12File(file)
            .setServiceAccountUser(ACCOUNT_USER)
            .build();
}

但是,凭证总是返回 accessToken null,我不能做任何操作。我收到一个错误的请求:

Exception in thread "main" java.lang.RuntimeException:   com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_grant"
}

我的客户代码:

private static AdSense initializeAdsense() throws Exception {
    // Authorization.
    Credential credential = getCredential();        
    String token = credential.getAccessToken();
    System.out.println(token);
    AdSense adsense = new AdSense.Builder(new NetHttpTransport(), JSON_FACTORY, credential).setApplicationName("Google-AdSenseSample/1.2").build();
    return adsense;
}

public static Accounts run(AdSense adsense, int maxPageSize) throws Exception {
    System.out.println("=================================================================");
    System.out.println("Listing all AdSense accounts");
    System.out.println("=================================================================");

    // Retrieve account list in pages and display data as we receive it.
    String pageToken = null;
    Accounts accounts = null;
    do {
        accounts = adsense.accounts().list().setMaxResults(maxPageSize).setPageToken(pageToken).execute();

        if ((accounts.getItems() != null) && !accounts.getItems().isEmpty()) {
            for (Account account : accounts.getItems()) {
                System.out.printf("Account with ID \"%s\" and name \"%s\" was found.\n", account.getId(), account.getName());
            }
        } else {
            System.out.println("No accounts found.");
        }

        pageToken = accounts.getNextPageToken();
    } while (pageToken != null);

    System.out.println();
    return accounts;
}

public static void test() throws Exception {
    AdSense adsense = initializeAdsense();
    run(adsense, 30);
}

问题是,到底有什么问题?

编辑: 也许我不能那样做。

恐怕不支持通过服务帐户身份验证访问 AdSense Management API,因为它是受保护的用户信息

https://groups.google.com/forum/#!msg/adsense-api/j-gQsp_fE94/CrOPhRLv4WUJ

4

1 回答 1

0

SERVICE_ACCOUNT_ID 应该是您的服务帐户的电子邮件地址 (xxxxxx@developer.gserviceaccount.com),并且不要设置 ACCOUNT_USER。

于 2012-12-20T11:24:40.037 回答