简体   繁体   English

无法使用Java代码从Google驱动器下载Google表格

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

Not able to download google sheet from google drive. 无法从Google云端硬盘下载Google表格。 Facing 403 Insufficient Permission issue. 遇到403权限不足问题。

Please check below code. 请检查以下代码。

    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 error is displayed after executing above code. 执行上述代码后,显示403错误。 Please check below output of above code. 请检查以下代码的输出。

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"
 }
}

Change the scope and data store directory. 更改范围和数据存储目录。

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

Added File path for saving the file to local machine. 添加了用于将文件保存到本地计算机的文件路径。

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

Above code helps for downloading file from google drive. 上面的代码有助于从Google驱动器下载文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM