You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:40:01