带有JSON Payload的Google Apps脚本UrlFetchApp

时间:2012-06-04 20:57:20

标签: json google-apps-script

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

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 个答案:

答案 0 :(得分:11)

我不理解服务器端错误,但'payload'参数必须是此处指定的字符串: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" }'
};

答案 1 :(得分:2)

  • 如果您将有效负载设置为字符串,它将直接传递(作为 UTF-8字符串)。
  • 如果您将有效负载设置为对象,它将被发送为 一个HTML表单(这意味着'application / x-www-form-urlencoded'如果是 字段很简单,如果Object包含a,则为'multipart / form-data' 斑点/文件)。

对于您的用例(服务器希望接收JSON),听起来像Utilities.jsonStringify()是可行的方法。

答案 2 :(得分:0)

这里的代码应该与一些重要的评论一起使用:

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)
    }
}

答案 3 :(得分:0)

类似的情况在类似情况下对我有用:

我没有创建有效载荷并添加到选项,而是将参数构建到字符串中以附加到URL:

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

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

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

因此,我的选项被传递,仅包含标题

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