3

我正在尝试从 Google Apps 脚本中查询 goo.gl API。我看到的问题是以下错误消息:

Request failed for https://www.googleapis.com/urlshortener/v1/url?key=AIXXXXXXXXXXXXXXXXXXXXXLmGJQw returned code 400. Server response: { "error": { "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." } } (line 28)

当我尝试在UrlFetchApp.fetch(post_url, options);.

这是我在 Google Apps 脚本中使用的实际编码。

function minifyGoogl(longUrl) {
  var post_url = 'https://www.googleapis.com/urlshortener/v1/url';

  var apiKey = UserProperties.getProperty('googl_api_key');

  if(!apiKey){
    var apiKey = ScriptProperties.getProperty('googl_api_key');
  }

  if(apiKey){
    post_url += '?key=' + apiKey;
  }

  var payload = Utilities.jsonStringify({'longUrl': longUrl });

  var options = {
    'method' : 'post',
    'headers' : {
      'Content-Type' : 'application/json'
    },
    'payload' : payload
  };

  try{
    var response = UrlFetchApp.fetch(post_url, options);
  }catch(e){
    if(e.message){
      throw e.message;
    }
  }

  var responseJson = response.getAs('json');
}
function testMinifyGoogl(){
  minifyGoogl('http://eduardo.cereto.net');
}
4

2 回答 2

3

文档contentType 默认为 'application/x-www-form-urlencoded'

也许尝试Content-Type使用参数设置而不是手动contentType插入标题?Content-Type

于 2011-07-04T00:55:34.557 回答
0

以下代码完美运行。

function ShortenUrl(){
var url = 'https://www.googleapis.com/urlshortener/v1/url';
var apiKey = 'AIzBlNS-3HZdxKgwj-x30';
url += '?key=' + apiKey;
var payload = {"longUrl":"www.google.com"};

var parameters = { method : 'post',
                payload:JSON.stringify(payload),
                contentType:'application/json',                    
                muteHttpExceptions:true};

var response = UrlFetchApp.fetch(url, parameters);
Logger.log(response);
}
于 2015-04-24T18:47:28.560 回答