2017-09-26 38 views
0

這是場景。我有一個帳戶,用於保存測試結果電子表格。我有一個服務帳戶,用於編程(使用java和谷歌驅動器apiv3)來添加/更新這些電子表格。我需要一種方法來創建電子表格並從服務帳戶中搜索用戶帳戶和文件夾中的電子表格。我有以下代碼獲取文件列表,但它是服務帳戶文件夾中的文件,而不是用戶帳戶文件夾。任何幫助?如何使用服務帳戶搜索文件/在另一個用戶文件夾中打開/創建Google表格?

private static boolean findSpreadsheetFile(String sSpreadsheetName) 
       throws GeneralSecurityException, IOException, URISyntaxException 
{ 
    String pageToken = null; 
    // Build a new authorized API client service. 
    Drive driveService = getDriveService(); 
    // Print the names and IDs 
    do 
    { 
     FileList result = driveService.files().list() 
         .setPageToken(pageToken) 
         .setFields("nextPageToken, files(id, name)") 
         .execute(); 
     for (com.google.api.services.drive.model.File file : result.getFiles()) 
     { 
      System.out.printf("Found file: %s (%s)\n", file.getName(), file.getId()); 
     } 
     pageToken = result.getNextPageToken(); 
    } 
    while (pageToken != null); 
    return true; 
} 

public static Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException 
{ 
    Credential credential = authorizeDrive(); 
    return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); 
} 

private static GoogleCredential authorizeDrive() throws GeneralSecurityException, IOException, URISyntaxException 
{ 
    JacksonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); 
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); 
    URL fileUrl = ParseTestResultsEmails.class.getResource(sP12Filename); 
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport) 
        .setJsonFactory(JSON_FACTORY).setServiceAccountId(sServiceAccountID) 
        .setServiceAccountPrivateKeyFromP12File(new File(fileUrl.toURI())) 
        .setServiceAccountScopes(DRIVE_SCOPES).build(); 
    return credential; 
} 

回答

0

似乎沒有辦法使用API​​在Google雲端硬盤中執行我想要的操作。我最終做的是創建表單作爲「服務帳戶」,然後將所有權轉讓給我想要的用戶,然後將其分享給需要訪問的組。這很好用!

1

從這個documentation基礎,域管理員可以使用服務帳戶使用OAuth 2.0下放權力這樣。

在企業應用程序中,您可能希望以編程方式訪問用戶數據,而無需任何人工授權。在G Suite域中,域管理員可以授予第三方應用程序對其用戶數據的域範圍訪問權 - 這被稱爲域範圍授權。

警告:服務帳戶只能用於執行委派,其中的有效標識是域中單個用戶的有效標識。使用服務帳戶作爲共同所有者來創建許多共享文檔可能會產生嚴重的性能影響。此外,服務帳戶可能不會獲得額外的存儲配額,也不會充當域的成員。

有關更多信息,您可能會看到Using OAuth 2.0 for Server to Server Applications文檔。

+0

我們不使用GSuite域名。我也不是域管理員。不幸的是,這是行不通的。 – GregMa

相關問題