用Python開發(fā)可用于iPhone的Google Reader API
而開發(fā)的第一步自然就是搞定Google Reader API,可惜Google一直沒有放出官方文檔。所幸的是前人已經(jīng)通過反向工程探尋出了相關(guān)信息(GoogleReaderAPI、Using the Google Reader API和GReader-Cocoa等),所以不用自己去一一摸索了。
不過文檔有點老了,這期間Google也稍微改了一些東西,所以還需要稍作修正。
由于現(xiàn)在手頭上沒有Mac,所以就不用Objective-C,而拿Python來演示。這樣代碼量也會少很多,邏輯顯得更加清晰。
在訪問之前需要證明你的身份,所以先去https://www.google.com/accounts/ClientLogin獲取登錄憑證。
此處需要POST 3個字段:service為'reader',Email為Google賬號,Passwd為密碼。此外還可以附加source字段用于標(biāo)明你的客戶端,其中網(wǎng)頁版是'scroll',iOS網(wǎng)頁版是'mobilescroll',你可以隨意改成其他字符串。
- from urllib import urlencode
- from urllib2 import urlopen, Request
- LOGIN_URL = 'https://www.google.com/accounts/ClientLogin'
- EMAIL = '你的郵箱'
- PASSWORD = '你的密碼'
- request = Request(LOGIN_URL, urlencode({
- 'service': 'reader',
- 'Email': EMAIL,
- 'Passwd': PASSWORD,
- 'source': 'mobilescroll'
- }))
- f = urlopen(request)
然后會拿到這樣一串字符串,一共3行:
- SID=...
- LSID=...
- Auth=...
這里我們需要SID和Auth,它們應(yīng)該是不會過期的,除非退出登錄:
- lines = f.read().split()
- sid = lines[0]
- auth = lines[2][5:]
拿到這2個字段后就可以使用Google Reader API了。具體方法就是訪問API地址(見GoogleReaderAPI文檔),然后把SID作為cookie,Auth作為Authorization。
例如獲取訂閱列表:
- headers = {'Authorization': 'GoogleLogin auth=' + auth, 'Cookie': sid}
- request = Request('https://www.google.com/reader/api/0/subscription/list?output=json', headers=headers)
- f = urlopen(request)
- print f.read()
就會拿到如下的信息:
- {"subscriptions":
- [{"id":"feed/供稿地址","title":"供稿名","categories":
- [{"id":"user/Google Reader用戶ID/label/分類名","label":"分類名"}],
- "sortid":"不知道啥玩意","firstitemmsec":"第一個條目的時間戳","htmlUrl":"供稿的網(wǎng)站地址"},...(其他供稿的信息)]}
不過如果要修改的話(一般是POST請求),還需要一個token參數(shù)。這個token與SID和Auth不同,它很容易過期。因此如果失效了,需要再次請求一個。
請求的地址是http[s]://www.google.com/reader/api/0/token,它可以附帶2個可選的GET參數(shù):ck是時間戳,client是客戶端名稱。
- request = Request('https://www.google.com/reader/api/0/token', headers=headers)
- f = urlopen(request)
- token = f.read()
拿到token后就可以進(jìn)行訂閱等操作了,例如訂閱本站:
- request = Request('https://www.google.com/reader/api/0/subscription/quickadd?output=json', urlencode({
- 'quickadd': 'http://www.scjtxx.cn',
- 'T': token
- }), headers=headers)
- f = urlopen(request)
- print f.read()
會拿到這樣的結(jié)果:
- {"query":"http://www.keakon.net/feed","numResults":1,"streamId":"feed/http://www.scjtxx.cn"}
再去看看你的Google Reader,應(yīng)該就訂閱好本站了。
原文:http://simple-is-better.com/news/565
【編輯推薦】