用Python开发可用于iPhone的Google Reader API


而开发的第一步自然就是搞定Google Reader API,可惜Google一直没有放出官方文档。所幸的是前人已经通过反向工程探寻出了相关信息(GoogleReaderAPI、Using the Google Reader API和GReader-Cocoa等),所以不用自己去一一摸索了。

不过文档有点老了,这期间Google也稍微改了一些东西,所以还需要稍作修正。

由于现在手头上没有Mac,所以就不用Objective-C,而拿Python来演示。这样代码量也会少很多,逻辑显得更加清晰。

在访问之前需要证明你的身份,所以先去https://www.google.com/accounts/ClientLogin获取登录凭证。

此处需要POST 3个字段:service为'reader',Email为Google账号,Passwd为密码。此外还可以附加source字段用于标明你的客户端,其中网页版是'scroll',iOS网页版是'mobilescroll',你可以随意改成其他字符串。

  1. from urllib import urlencode  
  2. from urllib2 import urlopen, Request  
  3.  
  4. LOGIN_URL = 'https://www.google.com/accounts/ClientLogin' 
  5. EMAIL = '你的邮箱' 
  6. PASSWORD = '你的密码' 
  7.  
  8. request = Request(LOGIN_URL, urlencode({  
  9.     'service''reader',  
  10.     'Email': EMAIL,  
  11.     'Passwd': PASSWORD,  
  12.     'source''mobilescroll' 
  13. }))  
  14.  
  15. f = urlopen(request) 

然后会拿到这样一串字符串,一共3行:

  1. SID=...  
  2. LSID=...  
  3. Auth=... 

这里我们需要SID和Auth,它们应该是不会过期的,除非退出登录:

  1. lines = f.read().split()  
  2. sid = lines[0]  
  3. auth = lines[2][5:] 

拿到这2个字段后就可以使用Google Reader API了。具体方法就是访问API地址(见GoogleReaderAPI文档),然后把SID作为cookie,Auth作为Authorization。

例如获取订阅列表:

  1. headers = {'Authorization''GoogleLogin auth=' + auth, 'Cookie': sid}  
  2. request = Request('https://www.google.com/reader/api/0/subscription/list?output=json', headers=headers)  
  3. f = urlopen(request)  
  4. print f.read() 

就会拿到如下的信息:

  1. {"subscriptions":
  2. [{"id":"feed/供稿地址","title":"供稿名","categories":
  3. [{"id":"user/Google Reader用户ID/label/分类名","label":"分类名"}],
  4. "sortid":"不知道啥玩意","firstitemmsec":"第一个条目的时间戳","htmlUrl":"供稿的网站地址"},...(其他供稿的信息)]} 

不过如果要修改的话(一般是POST请求),还需要一个token参数。这个token与SID和Auth不同,它很容易过期。因此如果失效了,需要再次请求一个。

请求的地址是http[s]://www.google.com/reader/api/0/token,它可以附带2个可选的GET参数:ck是时间戳,client是客户端名称。

  1. request = Request('https://www.google.com/reader/api/0/token', headers=headers)  
  2. f = urlopen(request)  
  3. token = f.read() 

拿到token后就可以进行订阅等操作了,例如订阅本站:

  1. request = Request('https://www.google.com/reader/api/0/subscription/quickadd?output=json', urlencode({  
  2.     'quickadd''http://www.51cto.com',  
  3.     'T': token  
  4. }), headers=headers)  
  5. f = urlopen(request)  
  6. print f.read() 

会拿到这样的结果:

  1. {"query":"http://www.keakon.net/feed","numResults":1,"streamId":"feed/http://www.51cto.com"

再去看看你的Google Reader,应该就订阅好本站了。

原文:http://simple-is-better.com/news/565

评论关闭