2012-06-30 62 views
1

我想打電話給谷歌URL縮短API在我的Python代碼:谷歌URL縮短API的Python返回錯誤

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。我在哪裏出錯了?

回答

5

您需要在POST發送JSON,而非URL編碼數據:

import json 

# Rest of your code 

headers, response = h.request(apiUrl, "POST", json.dumps(data), headers) 
+0

謝謝! @馬亭,PIETERS – jwesonga