【问题标题】:401 Unauthorized -cannot list Google Drive files401 Unauthorized - 无法列出 Google Drive 文件
【发布时间】: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


    【解决方案1】:

    正如SO question 中所述,您收到错误可能是因为您的访问令牌已过期,您必须使用刷新令牌获取一个新令牌。令牌到期可以通过调用refreshToken 来处理。如果该调用失败并出现“Invalid Credentials”错误,则问题可能是用户已撤销访问权限。对于撤销的访问权限以及令牌过期以外的所有问题,最好的补救措施是通过 OAuth 对话框重定向用户以重新授予访问权限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 2014-11-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      相关资源
      最近更新 更多