我想写一个应用程序来缩短网址。这是我的代码:
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']
当我运行代码以获取一个小 url 时,它会引发异常:urllib2.HTTPError: HTTP Error 400: Bad Requests
. 这段代码有什么问题?