1
我想訪問使用java谷歌api的Adsense管理API。但是,我有oauth2身份驗證的麻煩。與doc根據下面的代碼應該足夠:通過java服務訪問谷歌API api
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空,我不能做任何操作。我得到一個錯誤的請求:
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
但也許這是正確的答案,我已經試過了。在這種情況下,我得到: '異常在線程 「主」 了java.lang.RuntimeException:com.google.api.client.googleapis.json.GoogleJsonResponseException:403禁止 { 「代碼」:403, 「錯誤「:[{」域「:」全球「, 」消息「:」用戶沒有AdSense帳戶「, 」reason「:」noAdSenseAccount「 }], 」message「:」User does沒有AdSense帳戶。「 } \t at Test.main(Test.java:28)' – rdllopes