我想編寫一個應用程序來縮短網址。這是我的代碼:如何在Python中使用Google Shortener API
import urllib, urllib2
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = urllib.urlencode({'longUrl':url})
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
postdata,
headers
)
ret = urllib2.urlopen(req).read()
return json.loads(ret)['id']
當我運行代碼來獲得一個微小的網址,它拋出一個異常:urllib2.HTTPError: HTTP Error 400: Bad Requests
。 這段代碼有什麼問題?
感謝的urllib和urllib2的你reply.The API是真的ugly.actually,我寫的應用程序與請求,它也可以,但爲什麼我應該用json.dumps替換urllib.urlencode? – YuYang
,因爲'urlencode'傳遞由&所分隔的key:值,而google API期望的是像數據{key:value}這樣的json。 [urlencode](http://docs.python.org/2/library/urllib.html#urllib.urlencode) – PepperoniPizza
也許我應該更仔細地閱讀api文檔。非常感謝您...... – YuYang