YuY*_*ang 11 python google-api google-url-shortener
我想写一个应用程序来缩短网址.这是我的代码:
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']
Run Code Online (Sandbox Code Playgroud)
当我运行代码获取一个小url时,它抛出一个异常:urllib2.HTTPError: HTTP Error 400: Bad Requests.这段代码有什么问题?
Pep*_*zza 15
我尝试了你的代码并且无法使其工作,所以我用请求写了它:
import requests
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
print r.text
Run Code Online (Sandbox Code Playgroud)
编辑:使用urllib的代码:
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = {'longUrl':url}
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
json.dumps(postdata),
headers
)
ret = urllib2.urlopen(req).read()
print ret
return json.loads(ret)['id']
Run Code Online (Sandbox Code Playgroud)
小智 5
我知道这个问题很旧,但对Google来说却很高。
可以尝试的另一件事是pyshorteners库,它实现起来非常简单。
这里是一个链接:
https://pypi.python.org/pypi/pyshorteners
使用api密钥:
import requests
import json
def shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY)
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
return r.json()
Run Code Online (Sandbox Code Playgroud)