gpt4 book ai didi

java - Google Drive 公共(public) API 访问

转载 作者:太空宇宙 更新时间:2023-11-04 15:05:31 24 4
gpt4 key购买 nike

我需要我的网络应用程序的服务器能够在云端硬盘文件夹中创建电子表格,而无需任何用户干预。

使用我在开发人员控制台的 API 和身份验证部分中创建的公共(public) API 访问 key 是否可以实现这一点?

类似这样的事情:

    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();

谢谢。

最佳答案

答案是您需要创建一个服务帐户,然后就很容易了。请记住将 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();
}

关于java - Google Drive 公共(public) API 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22047585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com