【问题标题】:POST requests incomplete on Google scriptGoogle 脚本上的 POST 请求不完整
【发布时间】:2016-12-19 08:20:15
【问题描述】:

我正在尝试从 Google 表格中使用 urlFetchApp 发送 POST 请求。

我已经编写了下面的代码,但可以使它工作。每次运行此脚本时,我都会遇到以下错误-“code”:400,“message”:“Bad request:不完整的令牌请求”。我不明白,因为当我从 POSTMAN 运行相同的请求时,我得到了成功的答案。在飞行的客户 ID 中,我有特殊字符,如“/”和“+”,在 client_secret 中“!”,也许它来自那里?

感谢您的帮助!

---- GSheets 脚本 -----

function DX_API_request() {
  var payload  = {
    'grant_type': 'client_credentials',
    'client_id': 'name/a+@b.com',
    'client_secret': 'XXX!'
  }; 
  var options = {
    'method' : 'POST',
    'Accept': 'application/json',
    'payload' : JSON.stringify(payload),
    'muteHttpExceptions': true
  };
    Logger.log(JSON.stringify(payload));
    var test = UrlFetchApp.getRequest('https ://dx-example.com/admin/v100/api/oauth/token', options);
    Logger.log(test);
    var resquest_bearer = UrlFetchApp.fetch('https ://dx-example.com/admin/v100/api/oauth/token',options);
    Logger.log(resquest_bearer);
    var dataAll = JSON.parse(resquest_bearer.getContentText());
    Logger.log(dataAll.message);
}

----- Postman 中的 Curl 命令 --------

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Cache-Control: no-cache" -H "Postman-Token: 655d9932-4681-f23d-6caf-5fcf63c10b82" -d 'grant_type=client_credentials&client_id=name/a+@b.com&client_secret=XXX!' "https ://example.com/admin/v100/api/oauth/token"

【问题讨论】:

    标签: curl google-apps-script


    【解决方案1】:

    您在谷歌应用程序脚本中发出的请求与 curl 命令不同。

    在使用 curl 发出的请求中,您将内容类型设置为 application/x-www-form-urlencoded 并设置两个额外的标头:Cache-Control: no-cache Postman-Token: 655d9932-4681-f23d-6caf-5fcf63c10b82

    谷歌脚本中的相同请求会是这样的:

    var payload = {
        'grant_type': 'client_credentials',
        'client_id': 'name/a+@b.com',
        'client_secret': 'XXX!'
    };
    var options = {
        'method': 'post',
        'payload': payload,
        'headers': {
            "Cache-Control": 'no-cache',
            "Postman-Token": '655d9932-4681-f23d-6caf-5fcf63c10b82'
        }
    };
    var test = UrlFetchApp.getRequest('https://dx-example.com/admin/v100/api/oauth/token', options);
    Logger.log(test);
    

    主要问题可能是您的脚本将数据发布为application/json 而不是application/x-www-form-urlencoded。更多信息在这里:https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 2015-01-08
      • 2013-12-13
      • 1970-01-01
      相关资源
      最近更新 更多