gpt4 book ai didi

java - 带有服务帐户的 Google 电子表格

转载 作者:行者123 更新时间:2023-12-01 22:14:49 24 4
gpt4 key购买 nike

我想使用 Java Google 电子表格 API 访问 Google 云端硬盘上的电子表格。以前我使用客户端登录方法来登录,但现在这种方法已被弃用。现在,我尝试使用服务帐户进行身份验证,而无需与用户交互,因为该工具在后台运行,我需要自动化。但我无法让它工作。这些是我现在的代码。

    List<String> SCOPES_ARRAY = Arrays.asList(
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://docs.google.com/feeds",
"https://spreadsheets.google.com/feeds");
credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(
"xxxxxx@developer.gserviceaccount.com")
.setServiceAccountScopes(SCOPES_ARRAY)
.setServiceAccountPrivateKeyFromP12File(p12)
.setServiceAccountUser("me@gmail.com")
.build();
service = new SpreadsheetService("MonitorV3");
service.setOAuth2Credentials(credential);

SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");

worksheetFeed = service.getFeed(spreadsheet.getWorksheetFeedUrl(),
WorksheetFeed.class);

但是在执行最后一行时我遇到了空指针异常。刷新 token 出了问题。有人看到我做错了什么吗? enter image description here

我制作了一个独立的简单应用程序,现在我收到以下详细错误:

Exception in thread "main" com.google.gdata.util.AuthenticationException: Failed to refresh access token: 401 Unauthorized
at com.google.gdata.client.GoogleAuthTokenFactory$OAuth2Token.refreshToken(GoogleAuthTokenFactory.java:260)
at com.google.gdata.client.GoogleAuthTokenFactory.handleSessionExpiredException(GoogleAuthTokenFactory.java:702)
at com.google.gdata.client.GoogleService.handleSessionExpiredException(GoogleService.java:738)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:649)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at JavaApplication20.printDocuments(JavaApplication20.java:50)
at main.main(main.java:35)

最佳答案

GoogleCredential 目前已弃用。相反,如果您需要使用服务帐户访问 Google 表格,请使用 Google OAuth2 library .

使用示例:

// A few common declarations:
private static final String APPLICATION_NAME = "My Google Sheets Application";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS_READONLY);

// Initializing the service:
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredentials googleCredentials;
try(InputStream inputSteam = <YOURCLASS>.class.getResourceAsStream("/path/to/credentials/file.json")) {
googleCredentials = GoogleCredentials.fromStream(credentialsStream).createScoped(SCOPES)
}
Sheets service = Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpCredentialsAdapter(googleCredentials))
.setApplicationName(APPLICATION_NAME)
.build()

关于java - 带有服务帐户的 Google 电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31287911/

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