首页 > 解决方案 > 在应用程序脚本中使用标头发出 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")

提出这样一个请求的正确方法是什么?

参考: https ://bhagavadgita.io/api/

标签: google-apps-script

解决方案


405错误说明您无法使用当前 HTTP 动词查询该端点。

您应该指定您的.fetch方法正在发出POSTHttp 请求。

为此,您必须"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);

参考:

UrlFetchApp

休息


推荐阅读