我需要我的webapp服务器才能在Drive文件夹中创建电子表格而无需任何用户干预。
使用我在API& amp;中创建的公共API访问密钥是否可行。开发人员控制台的auth部分?
这样的事情:
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 :(得分:0)
答案是你需要创建一个serviceaccount然后很容易。请务必在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();
}