gpt4 book ai didi

java - 通过java google api 访问服务

转载 作者:行者123 更新时间:2023-12-01 04:57:03 30 4
gpt4 key购买 nike

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

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);
}

问题是,到底出了什么问题?

编辑:也许我就是做不到。

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 应是您的服务帐户的电子邮件地址 (xxxxxx@developer.gserviceaccount.com),并且不要设置 ACCOUNT_USER。

关于java - 通过java google api 访问服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13939169/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com