Using Google Apps Script to Post JSON Data

五迷三道 提交于 2019-11-30 07:03:57

Put in your options object a contentType like this:

 var options = { "method":"POST",
             "contentType" : "application/json",
            "headers": headers,
            "payload" : payload
           };

ContentType is one of the advanced parameters that the fetch method accepts. See more here.

It is pretty counter intuitive in UrlFetchApp syntax but this:

POST /api/ra/v1/ping HTTP/1.0
Host: app.kigo.net
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Type: application/json

Translates nicely to this curl:

curl https://app.kigo.net/api/ra/v1/ping -X POST -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" -H "Content-Type: application/json"

Translates to this in Google App Script:

    function myFunction() {

  var headers = { 
    "Authorization" : "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
  };

  var options =
   {
     "contentType" : "application/json",
     "method" : "post",
     "headers" : headers,
     "payload" : "test"
   };

  var response = UrlFetchApp.fetch("https://app.kigo.net/api/ra/v1/ping", options);  
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!