如何正确使用UrlFetchApp.fetch的google url shortener api?

时间:2015-03-04 15:41:41

标签: google-apps-script

我花了很多时间阅读谷歌手册和其他资源,并且在尝试使用此脚本获取简短网址时没有发现我做错了什么:

function test_short_link() {
  var apiKey, post_url, options, result;
  post_url = "https://www.googleapis.com/urlshortener/v1/url";
  apiKey = 'xxx';//here is real apiKey
  post_url += '?key=' + apiKey;
  var options =
     { 'method':'post',
       'headers' : {'Content-Type' : 'application/json'},
       "resource": {"longUrl": "https://google.com/"},
       'muteHttpExceptions': true
     }
   result = UrlFetchApp.fetch(post_url, options);
   Logger.log(result);
}

我做了各种修改,但它返回:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required",
    "locationType": "parameter",
    "location": "resource.longUrl"
   }
  ],
  "code": 400,
  "message": "Required"
 }
}
它让我发疯了!
请帮忙!这段代码有什么问题?

2 个答案:

答案 0 :(得分:2)

您需要修改此代码,因为它对longUrl进行硬编码并且不进行错误检查。一些重要的部分是API选项在UrlFetchApp选项对象的有效负载中发送,并且您需要在标头中传递当前用户OAuth令牌。

function ShortenUrl(){
var url = "https://www.googleapis.com/urlshortener/v1/url"

var payload = {"longUrl":"www.google.com"};

var parameters = { method : 'post',
                    headers : {'Authorization': 'Bearer '+ScriptApp.getOAuthToken()},
                    payload:JSON.stringify(payload),
                    contentType:'application/json',                    
                    muteHttpExceptions:true};

  var response = UrlFetchApp.fetch(url, parameters);
  Logger.log(response);

}

答案 1 :(得分:0)

还有一个advanced Google service可以更简单地完成。

您需要从脚本编辑器资源菜单中激活它(参见下图。)

代码就像那样简单:

function shortenUrl(longUrl) {
  var toShorten = UrlShortener.newUrl().setLongUrl(longUrl);
  var shortened = UrlShortener.Url.insert(toShorten);
  return shortened.id;
}

只需在下面的测试函数中使用它:

function test(){
  var shortUrl = shortenUrl("http://stackoverflow.com/questions/tagged/google-apps-script");
  Logger.log(shortUrl);
}

enter image description here

enter image description here