我正在尝试使用我的谷歌日历,并将每天作为文档发布到通过谷歌脚本的沃森发现。我的代码看起来像这样。
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"}}}"
答案 0 :(得分:1)
问题是Watson Discovery的文档必须作为multipart / form-data类型传递。以下函数将json文本(存储在jsonEvent.text中)写为发现文档。将api端点放在&new 39中。并将发现用户名和密码存储在' 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);
}