有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java中的Google Drive SDK API显示文件列表

我无法修复。。。您可以在下面找到代码:

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class getDriveService {


    /** Email of the Service Account */
    private static final String SERVICE_ACCOUNT_EMAIL = "<email_address_service>@developer.gserviceaccount.com";

    /** Path to the Service Account's Private Key file */
    private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "src/<file_key>-privatekey.p12";

    public static void main(String[] args) throws IOException, GeneralSecurityException, URISyntaxException {

        List<File> lista = null;

        lista = retrieveAllFiles(getDriveService());

        System.out.println(""+lista.size());
        for (File file : lista) {
            System.out.println(""+file.getId());
        }
    }

    /**
     * Build and returns a Drive service object authorized with the service accounts
     * that act on behalf of the given user.
     *
     * @param userEmail The email of the user.
     * @return Drive service object that is ready to make requests.
     */
    public static Drive getDriveService() throws GeneralSecurityException,
        IOException, URISyntaxException {

        Collection<String> elenco = new ArrayList<String>();
        elenco.add("https://www.googleapis.com/auth/drive");

        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(elenco)
                .setServiceAccountPrivateKeyFromP12File(
                        new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
                .build();
        Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
                .setApplicationName("FileListAccessProject")
                .setHttpRequestInitializer(credential).build();

        return service;
}

    /**
       * Retrieve a list of File resources.
       *
       * @param service Drive API service instance.
       * @return List of File resources.
       */
      private static List<File> retrieveAllFiles(Drive service) throws IOException {
        List<File> result = new ArrayList<File>();
        Files.List request = service.files().list();

        do {
          try {
            FileList files = request.execute();

            result.addAll(files.getItems());
            request.setPageToken(files.getNextPageToken());
          } catch (IOException e) {
            System.out.println("An error occurred: " + e);
            request.setPageToken(null);
          }
        } while (request.getPageToken() != null &&
                 request.getPageToken().length() > 0);

        return result;
      }


}

如果我运行main方法,它会显示“0”。文件列表为空。为什么

代码似乎是对的,我还从谷歌API控制台面板启用了服务“驱动API”。。。我禁用了“Drive SDK”(我不明白为什么,但这里https://developers.google.com/drive/delegation这么说)

怎么了?我忘了什么吗

提前感谢您的帮助

弗朗西斯科


共 (1) 个答案

  1. # 1 楼答案

    必须将ServiceAccountUser设置为要访问的用户驱动器,将ServiceAccountId设置为服务帐户用户

    比如:

    GoogleCredential credentialUser = new GoogleCredential.Builder().setTransport(httpTransport)
    .setJsonFactory(JSON_FACTORY)
    .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
    .setServiceAccountUser("user@gmail.com")
    .setServiceAccountPrivateKeyFromP12File(new File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
    .setServiceAccountScopes(serviceAccountScopes).build();