使用Google Apps Script从Google Drive JSON文件POST数据失败求助
问题分析与解决方案
你当前的核心错误是:把Google Drive文件的链接字符串直接用JSON.stringify()处理了,这会导致POST请求发送的内容是"https://drive.google.com/someJSONFILE.json"这类字符串,完全不是你需要的账单JSON数据。同时,Drive的普通分享链接无法直接通过UrlFetchApp获取文件内容,必须先正确获取文件里的JSON内容,再构造POST请求。
解决步骤
1. 获取Drive中JSON文件的实际内容
你需要先拿到文件里的JSON文本,而不是文件链接。这里提供两种可行方式:
方式一:用DriveApp通过文件ID获取(推荐)
从Drive文件链接中提取ID(比如链接https://drive.google.com/file/d/xxxxxx/view里的xxxxxx就是文件ID),然后用DriveApp读取内容:
// 替换成你的JSON文件ID const jsonFileId = "你的Google Drive文件ID"; // 获取文件并读取内容 const jsonFile = DriveApp.getFileById(jsonFileId); const jsonContent = jsonFile.getBlob().getDataAsString(); // 可选:将文本解析为JSON对象(后续stringify时更稳妥) const jsonData = JSON.parse(jsonContent);
方式二:用UrlFetchApp获取公开文件内容
如果你的JSON文件设置为公开可访问,可以构造直接下载链接来获取内容:
// 替换成你的文件ID const fileId = "你的Google Drive文件ID"; const downloadUrl = `https://drive.google.com/uc?export=download&id=${fileId}`; // 获取文件内容 const fileResponse = UrlFetchApp.fetch(downloadUrl); const jsonContent = fileResponse.getContentText(); const jsonData = JSON.parse(jsonContent);
2. 正确发送POST请求
拿到真实的JSON内容后,再构造请求发送:
const response = UrlFetchApp.fetch(url, { method: 'POST', muteHttpExceptions: true, // 用解析后的JSON对象转成字符串,或者直接传jsonContent(确保是合法JSON文本) payload: JSON.stringify(jsonData), headers: { Authorization: 'Bearer ' + service.getAccessToken(), 'Content-Type': 'application/json', Accept: 'application/json' } });
关键注意点
- 确保脚本有Drive文件访问权限:如果文件不是公开的,脚本运行者需要拥有该文件的查看/编辑权限。
- 不要省略
Content-Type: application/json:这是服务器识别JSON payload的必要头信息,你当前代码里的设置是正确的。
内容的提问来源于stack exchange,提问作者user22199192
相关产品推荐
相关产品推荐

