Post JSON 从 Google 应用程序脚本反对 Watson Discovery

Post JSON object to Watson Discovery from Google App Scripts

我正在尝试将我的 google 日历和 post 每天作为文档通过 google 脚本发送到 watson discovery。我的代码看起来像这样。

    var headers={
            "User-Agent": "CreateCalendarListJson",
            "Authorization": "Basic " + Utilities.base64Encode( authdata.username+":"+authdata.password)
        };
        //headers.contentType="application/json";
        var parms={"headers":headers};
        url=newurl+"/v1/environments/"+discoveryData.environmentID+
          "/collections/"+discoveryData.collection_ID+"/documents/?version=2017-09-01";
        parms.method="POST";
        parms.file={
          'value':JSON.stringify(jsonEvent),
          'options':{
            'filename':jsonEvent.filename,
            'contentType':"application/json"
          }
        }
        console.info('discovery add document %s',JSON.stringify(parms));
        response=UrlFetchApp.fetch(url,parms);

然而,这会得到错误 415 不支持的媒体类型。虽然 application/json 是受支持的类型,但我已经相应地设置了 contentType。有什么建议么?

当 UrlFetchApp.Fetch 为 运行 时,parms 变量如下所示:

{"headers":
     {"User-Agent":"CreateCalendarListJson",
      "Authorization":"Basic ZTIyNTEwM............................tHcg=="},
      "method":"POST",
      "file":{"value":"{\"title\":\"Events 10/13/2017\",\"filename\":\"Events_10_13_2017\",\"text\":[{\"date\":\"10/13/2017\",\"summary\":\"assignment 1\"}]}",
      "options":{"filename":"Events_10_13_2017",
       "contentType":"application/json"}}}"   

问题是必须将文档作为 multipart/form-data 类型传递给 Watson Discovery。下面的函数将写一个 json 文本(存储在 jsonEvent.text 中)作为发现文档。将 api 端点放在 'newurl' 中,并将发现用户名和密码存储在 'authdata'(json 对象)中,在 'filename' 中给出发现文档的文件名

function sendtodiscovery(url, jsonEvent, filename,authdata){
   var headers={
        "User-Agent": "CreateCalendarListJson",
        "Authorization": "Basic " + Utilities.base64Encode( authdata.username+":"+authdata.password)
    };
    var parms={"headers":headers};
    var boundary="xxxxxxxx";  
    parms.method="POST";
    var data="--"+boundary+"\r\n"
    data += "Content-Disposition: form-data; name=\"file\"; filename=\""+filename+"\"\r\n";
    data += "Content-Type: application/json\r\n\r\n";
    console.info("data=%s",data);
    console.info("event=%s",JSON.stringify(jsonEvent));
    var payload=Utilities.newBlob(data).getBytes()
    .concat(Utilities.newBlob(JSON.stringify(jsonEvent)).getBytes())
    .concat(Utilities.newBlob("\r\n--"+boundary+"--\r\n\r\n").getBytes());

    parms.contentType="multipart/form-data; boundary="+boundary;
    parms.payload=payload;
    //parms.muteHttpExceptions=true;
    console.info('discovery add document %s',JSON.stringify(parms));
    return UrlFetchApp.fetch(url,parms);
 }