【发布时间】:2016-12-23 12:05:25
【问题描述】:
我想将所有文件列出到我的 Google 云端硬盘帐户中。我尝试使用此代码:
@Test
public void hello() throws Exception
{
Drive service = getDriveService();
retrieveAllFiles(service);
}
private static final String SERVICE_ACCOUNT_EMAIL = "test@sonora-project.iam.gserviceaccount.com";
private static final String userEmail = "test@gmail.com";
public Drive getDriveService() throws GeneralSecurityException,
IOException
{
ClassLoader classLoader = this.getClass().getClassLoader();
java.io.File path = new java.io.File(classLoader.getResource("test-test123.p12").getFile());
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Arrays.asList(DriveScopes.DRIVE, DriveScopes.DRIVE_FILE, DriveScopes.DRIVE_METADATA))
.setServiceAccountUser(userEmail)
.setServiceAccountPrivateKeyFromP12File(path)
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setApplicationName("sonora project")
.setHttpRequestInitializer(credential).build();
return service;
}
private static List<File> retrieveAllFiles(Drive service) throws IOException
{
List<File> result = new ArrayList<File>();
Drive.Files.List request = service.files().list();
do
{
try
{
FileList files = request.execute();
result.addAll(files.getFiles());
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;
}
我在尝试列出文件时收到错误 401。你知道我该如何解决这个问题吗?
当我只运行身份验证部分时,代码正在运行。
【问题讨论】:
标签: java google-drive-api google-drive-realtime-api