如何使用服务帐户创建Google电子表格并与java中的其他Google用户共享?
我有一个应用程序,我通过Google服务帐户从Analytics API收集有关我网站的大量信息。 我的下一步是使用服务帐户创建电子表格,并与几个用户共享文档。
我已经在https://developers.google.com/google-apps/spreadsheets/上查看了该文档,但我找不到有关服务帐户和共享文档的任何内容。
所以我的第一个问题是可能的吗? 如果不是,我需要实施文档中举例说明的“使用我的个人帐户”吗? 如果是的话,请你提供一个例子吗?
谢谢!
有可能,请参见下面的示例(该示例确实需要进行一些调整):
创建驱动器服务:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY) .setServiceAccountId(confBean.getServiceAccountId()).setServiceAccountScopes("https://www.googleapis.com/auth/drive") .setServiceAccountPrivateKeyFromP12File(new File("path to the P12File")) .setServiceAccountUser("user@domain.com") .build(); Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
创建电子表格:
com.google.api.services.drive.model.File file = new com.google.api.services.drive.model.File(); file.setTitle("test"); file.setMimeType("application/vnd.google-apps.spreadsheet"); Insert insert = this.drive.files().insert(file); file = insert.execute();
创建电子表格服务:
GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY) .setServiceAccountId(confBean.getServiceAccountId()).setServiceAccountScopes("https://spreadsheets.google.com/feeds") .setServiceAccountPrivateKeyFromP12File(new File("path to the P12File")) .setServiceAccountUser("user@domain.com") .build(); SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1"); service.setOAuth2Credentials(credential);
检索工作表:
SpreadsheetService s = googleConn.getSpreadSheetService(); String spreadsheetURL = "https://spreadsheets.google.com/feeds/spreadsheets/" + file.getId(); SpreadsheetEntry spreadsheet = s.getEntry(new URL(spreadsheetURL), SpreadsheetEntry.class);
添加数据:
WorksheetFeed worksheetFeed = s.getFeed(spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class); List worksheets = worksheetFeed.getEntries(); WorksheetEntry worksheet = worksheets.get(0); URL cellFeedUrl= worksheet.getCellFeedUrl (); CellFeed cellFeed= s.getFeed (cellFeedUrl, CellFeed.class); CellEntry cellEntry= new CellEntry (1, 1, "aa"); cellFeed.insert (cellEntry);
另外,请参阅此相关问题
- 从Oauth2 Google Contacts API获取Userinfo
- 使用Google表格API和服务帐户时禁止使用403
- 使用工具:overrideLibrary =“org.springframework.android.rest.test”强制使用
- TokenResponseException:尝试访问Admin SDK Google API时出现401 Unauthorized Exception。
- 如何在我的Java应用程序中使用Google Translate API?
- 如何获取脱机令牌和刷新令牌以及自动刷新对Google API的访问权限
- 演讲到文本api其他语言android
- 我可以通过编程方式创建Google帐户吗?
- Java SSLException:证书中的主机名与www.googleapis.com不匹配