问题描述
我想使用de java Google电子表格API访问Google云端硬盘上的电子表格.过去,我使用客户端登录方法登录,但现在不赞成使用此方法.现在,我正在尝试使用服务帐户进行身份验证,而无需与用户进行交互,因为该工具在后台运行,因此我需要实现自动化.但是我无法正常工作.这些是我的代码.
I want to access a spreadsheet on Google Drive by using de java Google spreadsheet API. In the past i used the client login method to login but this method is deprecated now.Now I'm trying to use a service account to getting authenticated without interaction with the user because the tool is running in the background i needs to be automated. But i can't get it working. These my code now.
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(
"[email protected]")
.setServiceAccountScopes(SCOPES_ARRAY)
.setServiceAccountPrivateKeyFromP12File(p12)
.setServiceAccountUser("[email protected]")
.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);
但是执行最后一行时,我得到了nullpointerexception.刷新令牌出了点问题.有人看到我在做什么错吗?
But i'm getting a nullpointerexception when executing the last line. something goes wrong with refresh token. Is there someone seeing what i'm doing wrong?
我制作了一个独立的简单应用程序,现在出现以下详细错误:
I made a standalone simple application and now I get following detailded error:
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)
推荐答案
我通过使用以下代码解决了此问题:
I fixed this by using following code:
credential = new GoogleCredential.Builder()
.setTransport(transport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("618982716759-9ele96d95b7gqar6tn2ofa7jrjrudlol@developer.gserviceaccount.com")
.setServiceAccountPrivateKeyFromP12File(p12)
.setServiceAccountScopes(SCOPES_ARRAY).build();
credential.refreshToken();
因此没有.setServiceAccountUser("[email protected]").现在它可以正常工作了.
So without the .setServiceAccountUser("[email protected]"). Now it's working without any errors.
这篇关于带有服务帐户的Google Spreadsheet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!