如果需要管理 Web 上的资源,请使用 以下 UrlFetchApp 方法。
简单 GET 请求
如果只需要获取 Web 资源,请使用 fetch(url) 。
var response = UrlFetchApp.fetch('https://www.contoso.com');
该 fetch(url) 方法返回具有读取响应的方法的 HTTResponse 对象。 使用 getContentText 读取文本响应和 getContent 读取二进制响应的方法。
如果响应正文包含 JSON 对象,请用于 getContentText 获取 JSON 对象。 要访问 JSON 对象中的各个字段,请使用该 JSON.parse() 方法分析响应。
var stock = JSON.parse(response.getContentText());
Logger.log(`stock symbol: ${stock["symbol"]}`);
Logger.log(`company: ${stock["companyName"]}`);
Logger.log(`close price: ${stock["close"]}`);
处理 HTTP 错误
如果请求失败 (例如,有 400 Bad request) ,则服务将停止处理脚本并将错误消息写入日志。 该消息包括请求的 HTTP 状态代码,但不包括可能在响应正文中的错误消息。
如果需要获取响应正文,请改为调用 fetch(url, params) 该方法并将 muteHttpExceptions 参数设置为 true。 将 muteHttpExceptions 设置为 true 始终返回对脚本的控制。 然后,您需要调用该 getResponseCode() 方法来确定请求的成功或失败并采取相应的行动。
var response = UrlFetchApp.fetch('https://contoso.com', { muteHttpExceptions: true });
if (200 == response.getResponseCode())
{
Logger.log('HTTP request succeeded');
}
else
{
Logger.log('HTTP request failed');
}
添加、更新或删除 Web 资源
如果需要添加、更新或删除 Web 资源,请使用 提取 (url、参数) 方法。 通过此方法,可以指定要使用的 HTTP 谓词、Content-Type 标头、请求所需的任何其他标头以及请求的有效负载。 有关这些参数的详细信息,请参阅 UrlFetchParams 对象。
以下示例获取需要 OAuth 访问令牌的资源。 由于 GET 是提取方法的默认 HTTP 动词,因此唯一需要指定的参数就是 headers 参数。
var token = "<the oauth token goes here>";
var response = UrlFetchApp.fetch('https://contoso.com', { headers: { Authorization: `Bearer ${token}` } });
var jsonObject = JSON.parse(response.getContentText());
此示例发送带有 JSON 有效负载的 POST 请求。 由于有效负载是 JSON 对象,因此示例将 contentType 参数设置为 application/json。
var myData = {
'id' : '123abc',
'name' : 'leg',
'color' : 'red'
};
var options = {
'method' : 'post',
'contentType' : 'application/json',
'payload' : JSON.stringify(myData)
};
var response = UrlFetchApp.fetch('https://contoso.com', options);
var jsonObject = JSON.parse(response.getContentText());
使用 UrlFetchApp 从 OneDrive 获取数据文件或 CSV 文件。
若要从 OneDrive (https://onedrive.live.com) 中获取文件,请使用 Microsoft Graph。 访问 OneDrive 文件需要 OAuth 访问令牌。 获取访问令牌需要用户同意,除非你有刷新令牌。 但是,由于脚本不支持 UI 组件,因此你需要通过另一种方式获得同意。 如果尚无其他获取刷新令牌的方法,可以运行下面的 PowerShell 脚本来获取许可和刷新令牌。
$clientId = "your application ID goes here"
Start-Process "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=$clientId&scope=files.read offline_access&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf"
$code = Read-Host "Please enter the code"
$response = Invoke-WebRequest https://login.microsoftonline.com/common/oauth2/v2.0/token -ContentType application/x-www-form-urlencoded -Method POST -Body "client_id=$clientid&redirect_uri=https://login.live.com/oauth20_desktop.srf&code=$code&grant_type=authorization_code"
Write-Output "Refresh token: " ($response.Content | ConvertFrom-Json).refresh_token
需要先按照以下步骤获取客户端 ID,然后才能运行 PowerShell 脚本。
- 转到, https://apps.dev.microsoft.com 然后单击 “添加应用”。
- 输入应用名称,如 脚本客户端。 (不检查引导设置。)
- 单击 “创建 ”,记下应用程序 ID (客户端 ID) 。
- 单击“ 添加平台” ,然后单击 “本机应用程序”。
- 在 Microsoft Graph 委派的权限下,单击 添加 并选择 Files。阅读和offline_access。
- 单击保存。
打开记事本或喜欢的编辑器,然后将 PowerShell 脚本复制到编辑器。 设置为 $clientID 注册应用时收到的应用程序 ID。
$clientId = "abc123-4d9e-44f1-837d-a7244af50027"
保存文件并将其命名 GetTokens.ps1 (你可以为它命名,但扩展名必须 .ps1) 。
现在打开一个控制台窗口。 若要在 Microsoft Windows 上打开控制台窗口,请在 Windows 按钮+r) (<输入以下 Windows 运行>命令:
cmd.exe
在命令提示符下,导航到保存 GetTokens.ps1 的文件夹。 然后,输入以下命令。
powershell.exe -File .\GetTokens.ps1
如果遇到执行策略错误,则需要更改执行策略。 有关执行策略选项,请参阅 关于执行策略。 要更改会话的执行策略,请输入以下命令:
powershell.exe -ExecutionPolicy Bypass -File .\GetTokens.ps1
当 PowerShell 脚本成功运行时,它将启动一个浏览器会话,你可以在该会话中输入 Microsoft 帐户 (MSA) 凭据 (凭据必须有权访问你的 OneDrive 文件) 。 同意后,浏览器的地址栏将包含授权代码 (请参阅 ?code={copy this code}) 。
https://login.live.com/oauth20_desktop.srf?code=M7ab570e5-a1c0-32e5-a946-e4490c822954&lc=1033
将授权代码复制 (M7ab570e5-a1c0-32e5-a946-e4490c822954) ,然后在控制台窗口中的提示符将其输入。 然后,PowerShell 脚本返回刷新令牌。 在脚本中使用刷新令牌获取访问令牌。 应像对待密码一样对待刷新令牌;如果有人获取了该数据,他们就有权访问你的 OneDrive 数据。
刷新令牌长期有效,但也可能失效。 如果收到invalid_grant错误,则刷新令牌将不再有效,需要再次运行 PowerShell 脚本以获取许可和新的刷新令牌。
下载 CSV 文件的示例
获取刷新令牌后,下面的示例演示了如何 1) 使用刷新令牌获取访问令牌,以及 2) 调用 Microsoft Graph 来获取用于下载 CSV 文件的下载 URL。 将 {yourclientid} 替换为已注册应用的应用程序 ID,并将 {yourrefreshtoken} 替换为刷新令牌。
function main() {
var clientId = "{yourclientid}";
var refreshToken = "{yourrefreshtoken}";
var options = {
'method' : 'post',
'contentType' : 'application/x-www-form-urlencoded',
'payload' : `client_id=${clientId}&redirect_uri=https://login.live.com/oauth20_desktop.srf&refresh_token=${refreshToken}&grant_type=refresh_token`
};
// Use the refresh token to get the access token.
var response = UrlFetchApp.fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', options);
var tokens = JSON.parse(response.getContentText());
// Get the contents of the CSV file from OneDrive passing the access token in the Authorization header.
// Replace the path and file name (/me/drive/root/children/bids.csv) with your path and file name.
response = UrlFetchApp.fetch('https://graph.microsoft.com/v1.0/me/drive/root/children/bids.csv/content', { headers: { Authorization: `Bearer ${tokens['access_token']}` } });
// Read and parse the contents of the file. The parseCSV method is a placeholder for
// whichever method you provide to parse the file.
var file = response.getContentText();
var data = parseCSV(file);
}
分析 CSV 文件
没有内置的 CSV 解析工具,因此你需要自己编写或在线查找一个。 例如,在线快速搜索在 Stack Overflow 上找到 了这个 。 如果您在网上找到了一个,请确保它没有使用限制。
访问 Google 服务
有关使用 UrlFetchApp 访问 Google 服务的信息,请参阅 调用 Google 服务。