使用Google电子表格进行OAuth2身份validation时出现问题

我正在使用java库进行oauth2身份validation来访问谷歌电子表格。

我使用以下代码进行OAuth2身份validation:

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

获得“凭证”后,使用以下代码阅读电子表格:

 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。

如果我使用:

 service.setUserCredentials("email", "password"); 

代替oauth2身份validation,它给了我正确的结果。 不确定OAuth2身份validation有什么问题。 此外,当我从“凭证”对象打印“访问令牌”时,它会打印一个有效的访问令牌。

我用:

 spreadsheetService = new SpreadsheetService("cellmaster.com.au-v0.2"); spreadsheetService.setHeader("Authorization", "Bearer " + accessToken); 

而不是:

 spreadsheetService = new SpreadsheetService("cellmaster.com.au-v0.2"); spreadsheetService.setOAuth2Credentials(credential); 

我还必须为刷新令牌添加代码。 随着访问令牌即将到期。 但刷新令牌的工作方式与您期望的一样。