问题描述
我正在使用java库进行oauth2身份验证以访问Google电子表格。
I am using java library for oauth2 authentication for accessing google spreadsheet.
我使用以下代码进行OAuth2身份验证:
I am using below code for OAuth2 authentication:
credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token")
.setServiceAccountScopes("https://www.googleapis.com/auth/drive", "https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds")
.setServiceAccountPrivateKeyFromP12File(new File("xxxxx-privatekey.p12")).build();
获取凭证后,使用以下代码阅读电子表格:
After getting "credential", using below code to read spreadsheet:
SpreadsheetService service = new SpreadsheetService(
"MySpreadsheetIntegration");
service.setOAuth2Credentials(credential);
URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
System.out.println(feed.getTotalResults());
执行上面的代码会给我回到总结果0。
Executing above code give me back total result 0.
如果我使用:
service.setUserCredentials("email", "password");
代替oauth2身份验证,它给了我正确的结果。不确定OAuth2身份验证有什么问题。
此外,当我从凭证对象打印访问令牌时,它会打印一个有效的访问令牌。
in place of oauth2 authentication, it gives me back correct results. Not sure what is wrong with the OAuth2 authentication. Also when I print "access token" from "credential" object it prints a valid access token.
推荐答案
我使用:
spreadsheetService = new SpreadsheetService("cellmaster.com.au-v0.2");
spreadsheetService.setHeader("Authorization", "Bearer " + accessToken);
而不是:
spreadsheetService = new SpreadsheetService("cellmaster.com.au-v0.2");
spreadsheetService.setOAuth2Credentials(credential);
我还必须为刷新令牌添加代码。随着访问令牌即将到期。但刷新令牌可以正常运行。
also I had to add code for the refresh token. As the access token soon expires. But the refresh token works as you would expect.
这篇关于使用Google电子表格进行OAuth2身份验证时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!