Flutter调用Google Drive接口报错403:未认证用户调用日限额超出
Flutter调用Google Drive API 403报错解决方案
报错原因
返回的DetailedApiRequestError(status: 403, message: Daily Limit for Unauthenticated Use Exceeded)核心触发原因是:
你初始化DriveApi时使用的是无认证信息的普通http.Client,Google Drive API对未认证的请求有非常低的单日调用配额,配额耗尽后就会返回该报错。即使你访问的是公开的Drive资源,未认证请求的配额也很低,很容易触发限流。
解决方法
前置配置
- 登录Google Cloud控制台,创建对应项目后启用Google Drive API,根据你的应用运行平台(Android/iOS)配置OAuth 2.0客户端ID,填写应用包名、签名证书SHA-1等信息,下载平台对应的配置文件放到Flutter项目对应目录。
代码改造
- 项目pubspec.yaml中引入
google_sign_in和对应的Google API依赖,完成依赖安装。 - 替换原有的无认证HTTP客户端,使用用户登录后拿到的认证凭证构造认证客户端,再初始化DriveApi,示例代码如下:
import 'package:google_sign_in/google_sign_in.dart'; import 'package:googleapis/drive/v3.dart' as ga; import 'package:http/http.dart' as http; // 自定义带认证头的HTTP客户端 class GoogleAuthClient extends http.BaseClient { final Map<String, String> headers; final http.Client _client = http.Client(); GoogleAuthClient(this.headers); @override Future<http.StreamedResponse> send(http.BaseRequest request) { request.headers.addAll(headers); return _client.send(request); } } // 调用Drive API前先完成账号认证 Future<void> getDriveFiles() async { // 申请Drive访问权限 final GoogleSignIn googleSignIn = GoogleSignIn( scopes: [ga.DriveApi.driveScope], ); final GoogleSignInAccount? account = await googleSignIn.signIn(); if (account == null) return; final GoogleSignInAuthentication auth = await account.authentication; // 构造带认证token的客户端 final authClient = GoogleAuthClient( {'Authorization': 'Bearer ${auth.accessToken}'}, ); // 初始化DriveApi后调用接口 final ga.DriveApi driveApi = ga.DriveApi(authClient); final response = await driveApi.files.list(spaces: 'gdrv'); print('文件列表: ${response.files}'); }
可选方案
如果你只需要访问公开的Drive文件,不想触发用户登录流程,也可以在Google Cloud控制台创建API密钥,调用时将API密钥附加到请求参数中,不过该方式的调用配额远低于OAuth 2.0认证方式,仅适合低频次的公开资源访问场景。
内容的提问来源于stack exchange,提问作者MD Sarfaraj
相关产品推荐
相关产品推荐

