用于在python中获取重定向或最终URL的URL身份验证

时间:2014-04-03 07:51:18

标签: python

我正在使用google api来获取审核日志。代码工作正常并生成一个URL。 我将此URL粘贴到我的浏览器上,并要求提供g-mail登录授权。 授权后,它会将我重定向到新的URL。

我尝试使用python代码自动执行此操作,但在获取最终/重定向URL之前无法进行身份验证。

我尝试了以下代码,但没有成功:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

如何使用python验证并重定向到最终URL?

1 个答案:

答案 0 :(得分:0)

我会认真考虑使用python的requests库来访问API。请求Basic authentication很简单:

requests.get('http://api.foursquare.com/v1/user', auth=('username', 'password'))

它会自动跟踪任何重定向。我怀疑在使用foursquare api进行基本身份验证时需要遵循重定向,但如果需要,请求will do this too