简体   繁体   中英

Not able to download google sheet from google drive using java code

Not able to download google sheet from google drive. Facing 403 Insufficient Permission issue.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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