[英]Google Drive Public API access
I need the server of my webapp to be able to create a spreadsheet in a Drive folder without any user intervention. 我需要Web应用程序的服务器能够在Drive文件夹中创建电子表格,而无需任何用户干预。
Is this possible using the Public API access key I created in the APIs & auth section of the developers console? 是否可以使用我在开发人员控制台的“ API和身份验证”部分中创建的“公共API”访问密钥?
Something like this: 像这样:
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();
Thanks. 谢谢。
The answer is that you need to create a serviceaccount and then it is easy. 答案是,您需要创建一个服务帐户,然后这很容易。 Remember to add the Drive scope to the application in the google security console: https://admin.google.com/AdminHome#OGX:ManageOauthClients
请记住在Google安全控制台中将Drive作用域添加到应用程序中: 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.