我正在尝试使用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做到这一点。
答案 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)
对于您的用例(服务器希望接收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);
因此,我的选项被传递,仅包含标题。
对于我的项目,这就像一个魅力。