13

I am trying to post JSON data to the URL from google script but getting the above error:

Server response : HTTP Status 415 - Unsupported Media Type

My code:

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

I tried changing the content-type but didn’t work.

The authcode is working because I am able to GET from the URL.

4

2 回答 2

17

像这样添加到您optionscontentType对象:

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

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

于 2013-06-27T20:45:25.793 回答
5

这在 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 "Content-Type: 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);
}
于 2013-09-10T19:56:31.193 回答