1

我正在尝试使用我的谷歌日历并将每一天作为文档发布到通过谷歌脚本进行的沃森发现。我的代码看起来像这样。

    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"}}}"   
4

1 回答 1

1

问题是到 Watson Discovery 的文档必须作为 multipart/form-data 类型传递。以下函数将写入一个 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);
 }
于 2017-10-19T19:09:58.843 回答