使用Google Apps脚本发布JSON数据

时间:2013-06-27 19:45:55

标签: json google-apps-script http-post jira content-type

Server response  :  HTTP Status 415 - Unsupported Media Type

我正在尝试将谷歌脚本中的JSON数据发布到URL但是出现上述错误。 这是我的代码:

function myFunctionpost() {
  var url = "http://abc.xyz.org/jira/rest/api/2/issue";
  var data = {"project":{ "key": "KEY"},"summary": "create issue.", "description":                 "Creating of an issue from google spreadsheet using the REST API", "issuetype": {"name": "Bug"}}  ;
   var payload = JSON.stringify(data);

   var headers = { "Accept":"application/json", 
              "Content-Type":"application/json", 
              "Authorization":"Basic _authcode_"
             };

   var options = { "method":"POST",
                "headers": headers,
                "payload" : payload
               };
   var response = UrlFetchApp.fetch(url, options);
 Logger.log(response);  

 }

我尝试更改内容类型但没有用..auth代码正常工作,因为我可以从网址获取。

任何人都知道我哪里出错了?感谢。

2 个答案:

答案 0 :(得分:15)

在你的选项对象中输入一个这样的contentType:

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

ContentType是fetch方法接受的高级参数之一。查看更多here

答案 1 :(得分:3)

这在UrlFetchApp语法中非常直观,但是:

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

很好地转换到这个卷曲:

  

curl https://app.kigo.net/api/ra/v1/ping -X POST -H“授权:   基本dXNlcm5hbWU6cGFzc3dvcmQ =“ - H”内容类型:application / json“

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