无法使用java代码从谷歌驱动器下载谷歌表

时间:2017-05-14 09:27:54

标签: java google-drive-api drive

无法从谷歌硬盘下载谷歌表。面对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> 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"
 }
}

1 个答案:

答案 0 :(得分:1)

更改范围和数据存储目录。

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云端硬盘下载文件。