在Apps脚本中实施Google Custom Search API

时间:2016-01-19 17:39:46

标签: javascript rest google-apps-script google-custom-search

我希望在Google应用脚本中编写一个程序,通过定期发布"注释"来保持我的CSE实例的最新状态。包含某些网址的XML文件。我有一个格式正确的XML文件要发布到CSE,但我对如何使用Apps Script的UrlFetchApp授权帖子有点不清楚。这就是我到目前为止所拥有的:

  var userId = "my user ID";
  var cseID = "my custom search engine ID";
  var xml = an xml blob;
  var auth = ScriptApp.getOAuthtoken();
  var cseUrl = "http://cse.google.com/api/"+userId+"/annotations/"+cseID;

  var params = {
    "method"  : "POST",
    "contentType" : "application/xml; charset=utf-8",
    "payload" : xml,
    "muteHttpExceptions" : true,
    "Authorization" : "GoogleLogin auth=" + auth
  };

  var response = UrlFetchApp.fetch(cseUrl, params)

但是我得到<Error>You are not authorized to access this resource. If you feel this is an error, try re-logging into your Google Account.</Error>作为回复。应该&#34; auth&#34;在这种情况下,变量是我从ScriptApp.getOAuthToken()获得的身份验证令牌,还是来自Google开发人员信息中心的API密钥?

我一直在关注他们的教程here,但我对使用REST非常新,所以非常感谢任何指针。

1 个答案:

答案 0 :(得分:0)

您需要将Authorization添加到params对象的headers参数中。 https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#getRequest(String,Object)

检查下面的编辑。

var params = {
    "method"  : "POST",
    "contentType" : "application/xml; charset=utf-8",
    "payload" : xml,
    "muteHttpExceptions" : true,
    "headers":{"Authorization" : "GoogleLogin auth=" + auth}
  };