17

我正在尝试发布到期望使用 Google Apps 脚本将 JSON 作为有效负载的网络服务。我正在使用以下代码:

var options =
{
  "method" : "post",
  "contentType" : "application/json",
  "headers" : {
    "Authorization" : "Basic <Base64 of user:password>"  
  },
  "payload" : { "endDate": "2012-06-03" }
};

var response = UrlFetchApp.fetch("http://www.example.com/service/expecting/json", options);

在服务器端,我收到以下错误:

WARN [facade.SettingsServlet] 04 Jun 2012 15:30:26 - Unable to parse request body: endDate=2012-06-03
net.liftweb.json.JsonParser$ParseException: unknown token e

我假设服务器期望得到

{ "endDate": "2012-06-03" }

代替

endDate=2012-06-03

但我不知道如何UrlFetchApp做到这一点。

4

4 回答 4

18

我不明白服务器端错误,但“有效负载”参数必须是此处指定的字符串:https ://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch 。

尝试:

var options =
{
  "method" : "post",
  "contentType" : "application/json",
  "headers" : {
    "Authorization" : "Basic <Base64 of user:password>"  
  },
  "payload" : '{ "endDate": "2012-06-03" }'
};
于 2012-06-05T08:50:53.340 回答
3
  • 如果将有效负载设置为字符串,它将直接传递(作为 UTF-8 字符串)。
  • 如果将有效负载设置为对象,它将像 HTML 表单一样发送(如果字段很简单,则表示“application/x-www-form-urlencoded”,如果对象包含斑点/文件)。

对于您的用例(服务器期望接收 JSON),听起来 Utilities.jsonStringify() 是要走的路。

于 2012-06-06T14:45:00.350 回答
0

在类似的情况下,这样的事情对我有用:

我没有创建有效负载并添加到options,而是将参数构建到一个字符串中以附加到 URL:

var params = "id=2179853&price=62755";

然后,我将参数附加到 url 字符串:

var result = UrlFetchApp.getRequest(url + '?' + params, options);

因此,我的选项仅包含header传递。

对于我的项目,这就像一个魅力。

于 2019-11-08T20:21:36.827 回答
-1

下面是应该与一些重要注释一起使用的代码:

function testMe() {
    var products_authkey = "------------";
    try {
        var url = "https://app.ecwid.com/api/v1/---------/product?id=----------&secure_auth_key=" + products_authkey;
        //url= "http://requestb.in/----------"; // you can actually debug what you send out with PUTs or POSTs using Requestb.in service
        var payload = {
            id: "21798583", // id is necessary and should be a string, or it might be sent in scientific representation (with E)
            price: 62755
        }; 

        payload = JSON.stringify(payload); // the payload needs to be sent as a string, so we need this
        var options = {
            method: "put",
            contentType: "application/json", // contentType property was mistyped as ContentType - case matters
            payload: payload
        }; 
        var result = UrlFetchApp.getRequest(url, options);
        Logger.log(result) // a better way to debug
        var result = UrlFetchApp.fetch(url, options); // works perfectly in my case
        Logger.log(result)
    } catch (e) {
        Logger.log(e)
    }
}
于 2013-09-17T13:20:30.313 回答