UrlFetch的参数无效

时间:2012-12-07 02:05:25

标签: google-apps-script urlfetch

我正在尝试通过Google Apps脚本运行MongoLab(基于REST的MongoDB访问)查询。从记录器生成的URL如下所示   https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q= {“created_on”:{“$ gte”:“Thu Dec 06 00:00:00 PST 2012”,“$ lt”:“Thu Dec 06 23:59:59 PST 2012”}}
  当我在浏览器中输入此内容时,它可以正常工作并获取我正在寻找的响应。但是通过UrlFetchApp运行它会产生“无效参数”错误。我看到有几个帖子在同一行,但没有找到适合我的答案。 Javascript代码如下

//start and end are JS date objects  
var query = { created_on : {'$gte': start, '$lt' : end} };
var url = MONGO_LAB_URLS.MAIN + "&q=" + Utilities.jsonStringify(query);  
Logger.log("Query URL : " + url);  
var response = UrlFetchApp.fetch(url);  

我尝试过encodeURIComponent,但它没有用 - 可能是我做错了。有关如何克服这个问题的任何建议吗? 感谢。

2 个答案:

答案 0 :(得分:7)

无效参数即将发生,因为您在URL参数中发送了无效字符。您应该首先对参数进行编码。

我修改了你的代码并尝试运行。但由于invaliD API密钥很明显,它仍然失败了。您可以使用有效的API密钥尝试此代码。

//start and end are JS date objects
  MONGO_LAB_URLS = 'https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q=';
  var start = 'Thu Dec 06 00:00:00 PST 2012';
  var end = 'Thu Dec 06 23:59:59 PST 2012';

  var query = { created_on : {'$gte': start, '$lt' : end} };
  var url = MONGO_LAB_URLS + encodeURIComponent(Utilities.jsonStringify(query));  
  Logger.log("Query URL : " + url);  
  var response = UrlFetchApp.fetch(url);
  Logger.log(response);

我得到的回应是

Request failed for https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q=%7B%22created_on%22%3A%7B%22%24gte%22%3A%22Thu%20Dec%2006%2000%3A00%3A00%20PST%202012%22%2C%22%24lt%22%3A%22Thu%20Dec%2006%2023%3A59%3A59%20PST%202012%22%7D%7D returned code 400. Server response: { "message" : "Please provide a valid API key."}

答案 1 :(得分:0)

This为我工作,基本上只需添加以下行:

var urlEncoded = encodeURI(url);

然后致电

UrlFetchApp.fetch(urlEncoded);