簡體   English   中英

無法使用Java代碼從Google驅動器下載Google表格

[英]Not able to download google sheet from google drive using java code

無法從Google雲端硬盤下載Google表格。 遇到403權限不足問題。

請檢查以下代碼。

    public class Quickstart {

        /** Application name. */
        private static final String APPLICATION_NAME = "Drive API Java Quickstart";

        /** Directory to store user credentials for this application. */
        private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
                ".credentials/drive-java-quickstart");

        /** Global instance of the {@link FileDataStoreFactory}. */
        private static FileDataStoreFactory DATA_STORE_FACTORY;

        /** Global instance of the JSON factory. */
        private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

        /** Global instance of the HTTP transport. */
        private static HttpTransport HTTP_TRANSPORT;

        /**
         * Global instance of the scopes required by this quickstart.
         *
         * If modifying these scopes, delete your previously saved credentials at
         * ~/.credentials/drive-java-quickstart
         */
        private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);

        static {
            try {
                HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
                DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
            } catch (Throwable t) {
                t.printStackTrace();
                System.exit(1);
            }
        }

        /**
         * Creates an authorized Credential object.
         * 
         * @return an authorized Credential object.
         * @throws IOException
         */
        public static Credential authorize() throws IOException {
            // Load client secrets.
            InputStream in = Quickstart.class.getResourceAsStream("/client_secret.json");
            GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

            // Build flow and trigger user authorization request.
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
                    clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
            Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
            System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
            return credential;
        }

        /**
         * Build and return an authorized Drive client service.
         * 
         * @return an authorized Drive client service
         * @throws IOException
         */
        public static Drive getDriveService() throws IOException {
            Credential credential = authorize();
            return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
        }

        public static void main(String[] args) throws IOException {
            // Build a new authorized API client service.
            Drive service = getDriveService();

            // Print the names and IDs for up to 10 files.
            FileList result = service.files().list().setPageSize(10).setFields("nextPageToken, files(id, name)").execute();
            List<File> files = result.getFiles();
            if (files == null || files.size() == 0) {
                System.out.println("No files found.");
            } else {
                System.out.println("Files:");
                for (File file : files) {
                    System.out.printf("%s (%s)\n", file.getName(), file.getId());
                }
            }
            downloadFile(service, "1l0dX1hOdk0xX5T2ruqnci-75sMwziwiih9BFGX6DcdA");
        }

        private static void downloadFile(Drive service, String fileId) {

            try {
                File file = service.files().get(fileId).execute();

                System.out.println("Title: " + file.getName());
                System.out.println("Description: " + file.getDescription());
                System.out.println("MIME type: " + file.getMimeType());
                OutputStream outputStream = new ByteArrayOutputStream();
                service.files().export(fileId, "application/x-vnd.oasis.opendocument.spreadsheet")
                        .executeMediaAndDownloadTo(outputStream);
            } catch (IOException e) {
                System.out.println("An error occurred: " + e);
            }
        }

    }


    **Output:**

執行上述代碼后,顯示403錯誤。 請檢查以下代碼的輸出。

Credentials saved to /home/nikhil/.credentials/drive-java-quickstart
Files:

nikhil (1zNmRFWe_HABvhP_HukQIcOVdUoLllKB49RpPK3_XXn4)

Test Sheet (1l0dX1hOdk0xX5T2ruqnci-75sMwziwiih9BFGX6DcdA)

Getting started (0Bx8dATp9NaeXc3RhcnRlcl9maWxlX2Rhc2hlclYw)

Title: Test Sheet

Description: null

MIME type: application/vnd.google-apps.spreadsheet

An error occurred: com.google.api.client.http.HttpResponseException: 403 

Forbidden
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}

更改范圍和數據存儲目錄。

private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);

private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
                ".credentials/drive-java-quickstart.json");

添加了用於將文件保存到本地計算機的文件路徑。

public static void initialMethod() throws IOException {
        // Build a new authorized API client service.
        Drive service = getDriveService();
        downloadFile(service, "1JYlTtznsCll16upwIIbgXjqDvjsAFO5krSiGjvciO70");
    }


private static void downloadFile(Drive service, String fileId) {

        try {
            File file = service.files().get(fileId).execute();
            System.out.println("Title: " + file.getName());
            System.out.println("Description: " + file.getDescription());
            System.out.println("MIME type: " + file.getMimeType());
            OutputStream outputStream = new FileOutputStream(new java.io.File(Constant.DRIVE_EXCEL_PATH + "Test.xlsx"));
            service.files().export(fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    .executeMediaAndDownloadTo(outputStream);
            System.out.println(outputStream);
        } catch (IOException e) {
            System.out.println("An error occurred: " + e);
        } catch (Exception e) {
            System.out.println("An error occurred: " + e);
        }
    }

上面的代碼有助於從Google驅動器下載文件。

暫無
暫無

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

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