google 短网址服务 -- python版

记录一下 python实现google 网址服务的代码
#!/usr/bin/python 

import urllib2
import json
import sys
import os

url = sys.argv[len(sys.argv)-1]
shortenerURL = 'https://www.googleapis.com/urlshortener/v1/url'
longURL = json.dumps({'longUrl':url})

request = urllib2.Request(shortenerURL)
request.add_header('Content-Type','application/json')

opener = urllib2.build_opener()
output = opener.open(request,longURL).read()


doc = json.loads(output)
print output
short = doc['id']

print 'The short link %s' % short
ubuntu@ip-*****:/tmp$ python urlshort.py 
{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/NvLYt",
 "longUrl": "http://urlshort.py/"
}

The short link http://goo.gl/NvLYt

如果过程中出现404,大家懂的。

Fu*k GFW







你可能感兴趣的:(google 短网址服务 -- python版)