2013-06-28 36 views
11

我想編寫一個應用程序來縮短網址。這是我的代碼:如何在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。 這段代碼有什麼問題?

回答

16

我想你的代碼,並不能使它無論是工作,所以我requests寫的:

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 

編輯:代碼的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'] 
+0

感謝的urllib和urllib2的你reply.The API是真的ugly.actually,我寫的應用程序與請求,它也可以,但爲什麼我應該用json.dumps替換urllib.urlencode? – YuYang

+0

,因爲'urlencode'傳遞由&所分隔的key:值,而google API期望的是像數據{key:value}這樣的json。 [urlencode](http://docs.python.org/2/library/urllib.html#urllib.urlencode) – PepperoniPizza

+0

也許我應該更仔細地閱讀api文檔。非常感謝您...... – YuYang

2

擁有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() 
相關問題