I am trying to access Adsense Management API using java google-api. However, I having troubles with oauth2 authentication. According with the doc the following code should be enough:
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();
}
However, credential always returning accessToken null and I can't do any operation. I am getting a bad request:
Exception in thread "main" java.lang.RuntimeException: com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_grant"
}
My client code:
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);
}
The question is, after all, what is wrong?
Edited: Maybe I just cannot do that.
I'm afraid that accessing the AdSense Management API via service account authentication is not supported, since it's protected user information
https://groups.google.com/forum/#!msg/adsense-api/j-gQsp_fE94/CrOPhRLv4WUJ
SERVICE_ACCOUNT_ID should be email address of your service account ([email protected]) and do not set the ACCOUNT_USER.