簡體   English   中英

不使用OAuth將文件上傳到Java中的Google驅動器

[英]Upload file to google drive in java without OAuth

我想將文件上傳到Google雲端硬盤中的帳戶。 這個過程應該沒有人為干預。 有什么方法可以使用提供我的用戶名和密碼的Google Drive API在我的Google Drive中上傳文件嗎?

到目前為止,我所做的是:

  • 我在https://console.developers.google.com中創建了一個項目,並啟用了Google Drive API
  • https ://console.developers.google.com-> API和身份驗證->憑據中,我創建了一個新的客戶端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和備用鏈接,但文件未加載到我的帳戶中。 我將備用鏈接粘貼到瀏覽器中,但沒有權限。

您剛剛上傳的文件在哪里? 我應該更改些什么以指示最多我的帳戶驅動器? 我應該在哪里添加要與驅動器關聯的用戶名和密碼? 我應該如何對文件進行公開?

非常感謝您的關注。 我希望他們能幫助我。

您還需要在該項目上設置一個父項,例如“ root”,以便它們在“我的雲端硬盤”空間中顯示某人。 父級中的“ root”是用戶界面中的“我的雲端硬盤”。

在雲端硬盤界面中使用搜索進行確認,您應該發現它們已經上傳,但是由於您的代碼未添加父項,因此當前處於“未父項”狀態。

您正在將文件上傳到服務帳戶中。 如果您需要訪問該文件,則必須與您的電子郵件共享。 使用以下方法與您的電子郵件共享文件。

 public static void shareFileOrFolder(Drive service, File file)
        throws IOException {
    Permission newPermission = new Permission();

    newPermission.setEmailAddress("xxxxx@gmail.com");
    newPermission.setValue("xxxxx@gmail.com");
    newPermission.setType("user");
    newPermission.setRole("writer");
    service.permissions().insert(file.getId(), newPermission).execute();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM