如何通过urlfetchapp在有效负载中发送带有数组的发布请求

时间:2016-09-03 19:42:33

标签: google-apps-script

我需要模拟从html表单到页面的发布请求。我需要知道,如何在有效负载中正确发送数组。提前谢谢..

我有简单的html代码,这将是目标页面以这种方式收到的提交:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "Link[]": [
      "picturelink1.png", 
      "picturelink2.png", 
      "picturelink3.png"
    ], 
    "animationtype": "link", 
    "size": "400", 
    "speed": "0.4", 
    "usersize": "", 
    "userspeed": "0.1"
  }
}

我在GAS中编写了代码,它应该模拟相同的请求:

var payload =
      {       
        "Link[]":["jovianarchive_com/Content/Charts/621903744000000000_png","jovianarchive_com/Content/Charts/621903708000000000_png","jovianarchive_com/Content/Charts/621903816000000000_png"],  
        "animationtype":"link","size":"300","speed":"1","usersize":"","userspeed":""
      }

   var options =
   {
     "method" : "post",
     "payload" : payload
   };
  var result = (UrlFetchApp.fetch("http://httpbin.org/post", options).getContentText());

并返回此请求:

{
  "args": {},    
  "data": "",
  "files": {},
  "form": { "Link[]": "[Ljava.lang.Object;@536733f2",
  "animationtype": "link",
  "size": "300",
  "speed": "1",
  "usersize": "",
  "userspeed": ""
}

问题在于:

"form": { "Link[]": "[Ljava.lang.Object;@536733f2",

应该有这个:

  "form": {
    "Link[]": [
      "picturelink1.png", 
      "picturelink2.png", 
      "picturelink3.png"
    ], 

我还尝试将其字符串化并以JSON格式发送

"Content-type" : "application/json",

但它不会产生所需的输出..

它接收有效负载作为带引号的字符串:

 "args": {}, "data": "", "files": {}, "form": { "{\"Link[]\":[\"jovianarchive_com/Content/Charts/621903744000000000_png\",\"jovianarchive_com/Content/Charts/621903708000000000_png\",\"jovianarchive_com/Content/Charts/621903816000000000_png\"],\"animationtype\":\"link\",\"size\":\"300\",\"speed\":\"1\",\"usersize\":\"\",\"userspeed\":\"\"}": "" }, .....

thx任何帮助..

2 个答案:

答案 0 :(得分:1)

我找到了!!! haleluya .. 有效载荷必须以这种方式准备!我在制作解决方法PHP脚本时发现了这个解决方案。

  var payload =
      {       
        "Link[0]":"http://..",
        "Link[1]":"http://..",        
        "animationtype":"link","size":"300","speed":"1","usersize":"","userspeed":""
      }...

不是很直观,但效果很好!

接收的有效负载与HTML表单看起来不一样,但在我的情况下它有效!

{ "args": {}, "data": "", "files": {}, "form": 
{ 
"Link[0]": "http://jovianarchive.com/Content/Charts/621903744000000000_.png", 
"Link[1]": "http://jovianarchive.com/Content/Charts/621903708000000000_.png",
"animationtype": "link", "size": "300", "speed": "1", "usersize":` "","userspeed": "" }, .....

答案 1 :(得分:0)

如果您需要使用(key => value)发送数组,也可以使用类似的构造:

payload = {
    'fields[PRICE]': 2700
    ,'fields[NAME]': 'Name'
};

// to change it
payload['fields[PRICE]'] = 2845;