如果您的帐户是私人帐户而不是Google Workspace(以前称为G Suite)的一部分,则drinkmystery的答案 是正确的方法。否则,有一种更简洁的方法可以使用createDelegated()
方法来解决这个问题。此处有详细描述,并且您应该按照那里的所有配置说明进行操作,但是提供的代码示例基于一些已弃用的软件包,因此我花了一些时间将其与Drive API教程中的代码样本结合起来使其正常工作。
因此,对于只需要一个工作代码示例的人,这是它(请注意使用createDelegated
):
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.ServiceAccountCredentials;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
public class DelegatedDriveWithServiceAccountQuickstart {
private static final String APPLICATION_NAME = "your awesome app";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
private static final String CREDENTIALS_FILE_PATH = "/path/to/your/service-account-key-downloaded-from-google-api-console.json";
public static void main(String... args) throws IOException, GeneralSecurityException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(ServiceAccountCredentials.fromStream(new FileInputStream(CREDENTIALS_FILE_PATH))
.createScoped(SCOPES)
.createDelegated("user.whose.drive.you.want.to.share@your-domain-in-gsuite.com"));
Drive driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
FileList result = driveService.files().list()
.setPageSize(10)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
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());
}
}
}
}
请确保您的项目依赖项是最新的(不要盲目使用Drive API教程中的依赖项)。这是我的build.gradle文件:
apply plugin: 'java'
apply plugin: 'application'
mainClassName = 'DelegatedDriveWithServiceAccountQuickstart'
sourceCompatibility = 1.8
targetCompatibility = 1.8
version = '1.0'
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.api-client:google-api-client:1.31.1'
compile 'com.google.apis:google-api-services-drive:v3-rev20201130-1.31.0'
compile 'com.google.auth:google-auth-library-oauth2-http:0.22.2'
}