Google Apps Script调用Google Cloud API:如何绕过UrlFetch配额限制?
绕过UrlFetch配额访问Google Cloud Vision API的方法
绝对有办法解决这个问题!UrlFetch的带宽配额确实容易成为瓶颈,尤其是调用像Vision API这类需要传输图片的服务时。下面是两种可靠的方案:
1. 使用Google Apps Script高级服务(推荐)
这是最简单的官方解决方案,高级服务是Google专门为Apps Script集成的Cloud API客户端,完全绕过UrlFetch的配额限制,直接使用你Google Cloud项目的API配额。
步骤如下:
- 打开你的Apps Script编辑器,点击菜单栏的「扩展」>「高级Google服务」
- 在弹出的窗口里找到「Cloud Vision API」,开启开关后点击「确定」
- 接下来就可以用原生的方法调用API,不用自己写UrlFetch请求了,示例代码:
function callVisionAPI() { // 准备图片数据(这里用Base64编码的示例,也可以用Google Drive文件ID) const imageContent = Utilities.base64Encode(UrlFetchApp.fetch("https://example.com/test-image.jpg").getContent()); const request = { requests: [ { image: { content: imageContent }, features: [{ type: "LABEL_DETECTION", maxResults: 5 }] } ] }; // 直接调用高级服务 const response = Vision.images.annotate(request); console.log(response); }
这种方式的好处是:代码更简洁,不用处理OAuth认证(Google自动帮你搞定),配额直接和你的Cloud项目绑定,你可以在Cloud Console里查看和调整Vision API的配额。
2. 使用服务账号OAuth 2.0认证调用API
如果你需要更灵活的控制(比如用特定的服务账号权限,或者完全独立于Apps Script的默认配额),可以用服务账号来认证,直接调用API的REST端点,这时走的是你Cloud项目的带宽,不受UrlFetch的配额限制。
步骤概要:
- 登录Google Cloud Console,找到你的项目,创建一个服务账号,下载JSON格式的密钥文件
- 在Apps Script编辑器里添加OAuth2库(脚本编辑器>扩展>库,输入项目ID:
1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF,选择最新版本) - 编写代码加载服务账号密钥,获取访问令牌,然后用UrlFetch调用API(但此时的配额属于你的Cloud项目,不是Apps Script的UrlFetch配额)
示例代码片段:
function callVisionWithServiceAccount() { const serviceAccountKey = { /* 把你下载的JSON密钥内容粘贴到这里 */ }; const service = OAuth2.createService('VisionService') .setTokenUrl('https://oauth2.googleapis.com/token') .setPrivateKey(serviceAccountKey.private_key) .setIssuer(serviceAccountKey.client_email) .setPropertyStore(PropertiesService.getScriptProperties()) .setScope('https://www.googleapis.com/auth/cloud-vision'); if (service.hasAccess()) { const imageContent = Utilities.base64Encode(UrlFetchApp.fetch("https://example.com/test-image.jpg").getContent()); const requestBody = { requests: [ { image: { content: imageContent }, features: [{ type: "LABEL_DETECTION", maxResults: 5 }] } ] }; const options = { method: 'POST', headers: { Authorization: `Bearer ${service.getAccessToken()}` }, contentType: 'application/json', payload: JSON.stringify(requestBody) }; const response = UrlFetchApp.fetch('https://vision.googleapis.com/v1/images:annotate', options); console.log(JSON.parse(response.getContentText())); } else { console.error(service.getLastError()); } }
重要注意事项
- 不管用哪种方法,Google Cloud Vision API本身的配额还是存在的,你需要在Cloud Console里确认你的项目有足够的配额(比如请求次数、图片大小限制等)
- 使用高级服务前,确保你的Cloud项目已经启用了Cloud Vision API(如果没启用,高级服务开启时会提示你去启用)
- 服务账号方式需要确保服务账号拥有「Cloud Vision API User」或类似的角色,否则会有权限错误
内容的提问来源于stack exchange,提问作者Richard
相关产品推荐
相关产品推荐

