我正在尝试从云端硬盘获取文件数据列表。 按照谷歌的例子不起作用。
这是我的代码示例:
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private Drive createDriveService() throws IOException, GeneralSecurityException
{
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
InputStream in = ImageImpl.class.getResourceAsStream(USER_CREDENTIALS_FILE_PATH);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, Collections.singleton(DriveScopes.DRIVE))
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(applicationName)
.build();
}
public void listFiles() throws IOException, GeneralSecurityException
{
Drive service = createDriveService();
FileList result = service.files().list()
.setPageSize(10)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
}
输出:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
GET https://www.googleapis.com/drive/v3/files?fields=nextPageToken,%20files(id,%20name)&pageSize=10
{
"code": 403,
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT",
"domain": "googleapis.com",
"metadata": {
"service": "drive.googleapis.com",
"method": "google.apps.drive.v3.DriveFiles.List"
}
}
],
"errors": [
{
"domain": "global",
"message": "Insufficient Permission",
"reason": "insufficientPermissions"
}
],
"message": "Request had insufficient authentication scopes.",
"status": "PERMISSION_DENIED"
}
有什么想法吗?
我尝试在这里测试查询 -> https://developers.google.com/drive/api/reference/rest/v2/files/list并且工作正常,但在本地不行 另外,我使用相同的凭据通过 ID 访问工作表并且可以工作,这样就可以告诉我身份验证没问题,唯一的区别是范围。
转到 TOKENS_DIRECTORY_PATH 并删除那里的文件。
您之前授权了您的应用程序,然后更改了范围。
您的应用需要再次请求用户授权并请求新的范围。