2014-02-26 172 views
1

我需要我的web應用程序的服務器能夠在沒有任何用戶干預的情況下在Drive文件夾中創建電子表格。Google Drive公共API訪問

使用我在開發人員控制檯的API & auth部分創建的公共API訪問密鑰,可以實現這種可能性嗎?

事情是這樣的:

Credential credential = new GoogleCredential().setAccessToken(apiAccessKey); 

    client = new Drive.Builder(httpTransport, JSON_FACTORY, credential) 
      .setApplicationName(APPLICATION_NAME).build(); 

    File body = new File(); 
    body.setTitle(name); 
    body.setMimeType("application/vnd.google-apps.spreadsheet"); 
    body.setParents(Arrays.asList(new ParentReference() 
      .setId(folder))); 

    File file = client.files().insert(body).execute(); 
    return file.getId(); 

感謝。

回答

0

答案是你需要創建一個serviceaccount然後它很容易。請記住將Drive範圍添加到Google安全控制檯中的應用程序:https://admin.google.com/AdminHome#OGX:ManageOauthClients

private static final String USER_ACCOUNT_EMAIL = "xxxx"; 
private static final String SERVICE_ACCOUNT_EMAIL = "xxxx"; 
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/src/main/resources/xxxx"; 
private Drive getDriveService() 
     throws GeneralSecurityException, IOException, URISyntaxException { 
    HttpTransport httpTransport = new NetHttpTransport(); 
    JacksonFactory jsonFactory = new JacksonFactory(); 

    Set<String> scopes = new HashSet<String>(); 
    scopes.add(DriveScopes.DRIVE); 
    GoogleCredential credential = new GoogleCredential.Builder() 
      .setTransport(httpTransport) 
      .setJsonFactory(jsonFactory) 
      .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) 
      .setServiceAccountScopes(scopes) 
      .setServiceAccountUser(USER_ACCOUNT_EMAIL) 
      .setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH)) 
      .build(); 
    Drive service = new Drive.Builder(httpTransport, jsonFactory, null) 
      .setHttpRequestInitializer(credential).build(); 
    return service; 
} 

@Override 
public String createBlankSheet(String name, String folder) 
     throws Exception { 

    Drive client = getDriveService(); 

    File body = new File(); 
    body.setTitle(name); 
    body.setMimeType("application/vnd.google-apps.spreadsheet"); 

    File file = client.files().insert(body).execute(); 
    return file.getId(); 
}