1

我正在尝试在我的 python 代码中调用 Google URL Shortener API:

def shorternUrl():
        API_KEY = "AIzaSyCvhcU63u5OTnUsdYaCFtDkcutNm6lIEpw"
        apiUrl = 'https://www.googleapis.com/urlshortener/v1/url'
        longUrl = "http://www.cnn.com"
        headers = {"Content-type": "application/json"}
        data = {"longUrl": longUrl}
        h = httplib2.Http('.cache')
        try:
            headers, response = h.request(apiUrl, "POST", urllib.urlencode(data), headers)
            print response

        except Exception, e:
            print "unexpected error %s" % e

但我不断收到此错误:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "Parse Error"
   }
  ],
  "code": 400,
  "message": "Parse Error"
 }
}

我没有使用适用于 Python 的 Google API。我哪里错了?

4

1 回答 1

5

You need to send JSON in a POST, not URL encoded data:

import json

# Rest of your code

headers, response = h.request(apiUrl, "POST", json.dumps(data), headers)
于 2012-06-30T22:12:05.573 回答