我想将所有文件列入我的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。你知道我怎么解决这个问题吗?
当我只运行身份验证部分时,代码正在运行。
答案 0 :(得分:0)
正如此SO question中所述,您可能因为访问令牌过期而导致错误,并且您必须使用刷新令牌获取新错误。可以通过调用refreshToken
来处理令牌到期。如果该呼叫失败并且出现&#34;无效凭证&#34;错误,问题可能是用户已撤销访问权限。对于撤销访问和令牌到期以外的所有问题,最好的解决方法是重定向用户通过OAuth对话框重新授予访问权限。