401 Unauthorized -cannot list Google Drive files

514 Views Asked by At

I want to list all files into my Google Drive account. I tried to use this code:

@Test
public void hello() throws Exception
{
    Drive service = getDriveService();
    retrieveAllFiles(service);
}

private static final String SERVICE_ACCOUNT_EMAIL = "[email protected]";
private static final String userEmail = "[email protected]";

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;
}

I get error 401 when I try to list the files. Do you know how I can fix this?

When I run only the authentication part the code is working.

1

There are 1 best solutions below

0
On

As stated in this SO question, you're getting an error maybe because your access token expires and you'll have to get a new one using the refresh token. Token expiry can be handled by calling refreshToken. If that call fails with an "Invalid Credentials" error, the issue is probably that the user has revoked access. For revoked access and all issues other than token expiry, the best remedy is to redirect the user through the OAuth dialog to re-grant access.