更新时间:2022-12-22 14:08:21
好的,我找到了解决问题的方法.
Ok, I've found solution for my problem.
当然,我的应用是 Android 应用,我不想让用户登录/使用任何凭据连接到我的云端硬盘,最后我可以使用默认的云端硬盘网络应用操作文件.
Of course my app is an Android one, I dont'n want make user to log in/use any credentials to connect to my Drive, and lastly I can manipulate files using default Drive web app.
实现 Drive 服务 getter:
Implement Drive service getter:
public Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(G_SERVICE_EMAIL)
.setServiceAccountScopes(DriveScopes.DRIVE)
.setServiceAccountPrivateKeyFromP12File(PKC_12_FILE)
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential)
.build();
return service;
}
G_SERVICE_EMAIL 是 API 访问站点 的电子邮件地址,PKC_12_FILE 是之前下载的私钥.
Where G_SERVICE_EMAIL is email address from API Access site and PKC_12_FILE is previously downloaded private key.
允许您的服务从您的云端硬盘访问文件夹:在 云端硬盘应用中文件夹的共享选项中允许具有电子邮件的用户:G_SERVICE_EMAIL 读/写访问权限.
Allow your service to access folder from your Drive: in sharing options of the folder in Drive app allow user with email: G_SERVICE_EMAIL read/write access.
private File getTempPkc12File() throws IOException {
InputStream pkc12Stream = getAssets().open("this-is-your-unique-hash-privatekey.p12");
File tempPkc12File = File.createTempFile("temp_pkc12_file", "p12");
OutputStream tempFileStream = new FileOutputStream(tempPkc12File);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = pkc12Stream.read(bytes)) != -1) {
tempFileStream.write(bytes, 0, read);
}
return tempPkc12File;
}