【发布时间】:2014-10-01 17:06:32
【问题描述】:
我想将文件上传到我在 Google Drive 中的帐户。这个过程应该没有人为干预。有没有办法使用提供我的用户和密码的 google drive api 在我的 google drive 中上传文件?
到目前为止我做了什么:
- 我在https://console.developers.google.com创建了一个项目并启用了google drive api
- 在https://console.developers.google.com -> APIs & Auth -> Credentials 我创建了一个新的客户端 ID,在应用程序类型中我选择了服务帐户并下载了 pkcs12 密钥。
-
我有下一个代码:
/** * Email of the Service Account */ private static final String SERVICE_ACCOUNT_EMAIL = "account_of_service_account@developer.gserviceaccount.com"; /** * Path to the Service Account's Private Key file */ private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/path/to/pkcs12/donloaded.pkcs12"; /** * Build and returns a Drive service object authorized with the service * accounts. * * @return Drive service object that is ready to make requests. */ public static Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); List<String> scopes = new ArrayList<String>(); scopes.add(DriveScopes.DRIVE); GoogleCredential credential; credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(jsonFactory) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(scopes) .setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH)) .build(); Drive service = new Drive.Builder(httpTransport, jsonFactory, null) .setHttpRequestInitializer(credential).build(); return service; } public static void main(String[] args) throws GeneralSecurityException, IOException, URISyntaxException { Drive client = getDriveService(); File body = new File(); body.setTitle("mytitle"); body.setMimeType("application/vnd.google-apps.spreadsheet"); File file = client.files().insert(body).execute(); System.out.println(file.getId()); System.out.println(file.getAlternateLink()); }
当我运行代码时,结果是好的,我得到了文件的 id 和备用链接,但文件没有加载到我的帐户中。我将备用链接粘贴到浏览器中,但我没有权限。
您刚刚上传的文件在哪里?我应该更改什么以指示我的帐户驱动器?我应该在哪里添加我的用户名和密码以与我的驱动器关联?我应该如何处理文件才能公开?
非常感谢您的关注。我希望他们能帮助我。
【问题讨论】:
标签: java google-drive-api