google-apps-script - 在应用程序脚本中使用标头发出 curl 请求
问题描述
我正在尝试使用应用程序脚本发出 curl 请求,其官方指南的链接如下。这是查询:
curl -X POST "https://bhagavadgita.io/auth/oauth/token" -H "accept: application/json" -H "content-type: application/x-www-form-urlencoded" -d "client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=client_credentials&scope=verse"
根据官方指南:
如何获取访问令牌?
向 /auth/oauth/token 发出 POST 请求,这些参数在 Headers -
Client ID - 在注册应用程序后从 Account Dashboard 中获取。
Client Secret - 在注册应用程序后从 Account Dashboard 获得。
授予类型 - 使用客户端凭据。
范围 - 如果您只想访问经文,请使用 verse;如果您只想访问章节,请使用章节;如果您想同时访问两者,请使用章节。
我编写了如下代码:
function myFunction() {
var data = {
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
'header':{
'client_id':'MY-CLIENT-ID',
'client_secret':'MY-CLIENT-SECRET',
'grant_type':'client_credentials',
'scope':'verse'
}
};
var response = UrlFetchApp.fetch('https://bhagavadgita.io/auth/oauth/token', data);
Logger.log(response.getContentText());
}
我收到如下错误:
Exception: Request failed for https://bhagavadgita.io returned code 405. Truncated server response: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>405 Method Not Allowed</title> <h1>Method Not Allowed</h1> <p>The method is not allo... (use muteHttpExceptions option to examine full response) (line 13, file "Code")
提出这样一个请求的正确方法是什么?
解决方案
405
错误说明您无法使用当前 HTTP 动词查询该端点。
您应该指定您的.fetch
方法正在发出POST
Http 请求。
为此,您必须"method" : "post"
在获取选项的参数中指定:
var data = {
'client_id':'MY-CLIENT-ID',
'client_secret':'MY-CLIENT-SECRET',
'grant_type':'client_credentials',
'scope':'verse'
}
var options = {
"method" : "post",
"accept": "application/json",
"content-type": "application/x-www-form-urlencoded",
"payload" : data
}
var response = UrlFetchApp.fetch('https://bhagavadgita.io/auth/oauth/token', options);
参考:
推荐阅读
- powershell - 创建用户时将AD用户添加到组?
- ruby - 我可以在这里使用 .select(&) 方法吗?
- php - 如何从php中数据库的数组列返回唯一值
- arrays - 需要从长字符串中快速获取某些单词
- python - 如何根据另一列的值查找具有开始日期和结束日期的时间序列 Pandas 数据帧中的链?
- azure - Azure DevOps MS 托管代理查询仅锁定到内部 IP 的网站?
- python - “重置” tkinter 窗口
- c++ - 在 Linux 中通过串行端口进行通信很困难
- java - 为嵌套关系配置多段 @RepositoryRestResource 路径
- python - 拆分包含许多时间步长的 CSV 行