我试图在Http标头中添加身份验证然后执行http帖子,目标网址是这样的Github API:https://api.github.com/user
,下面的代码总是响应401,未经授权,我的问题是,如何在标题中添加身份验证?我的方式是否正确?
username = raw_input('Github name: ')
token = raw_input('Access Token: ')
url = 'https://api.github.com/user'
values = {"Username":username,"Password":token}
data = urllib.urlencode(values)
req = urllib2.Request(url,data)
response = urllib2.urlopen(req)
the_page = response.read()
答案 0 :(得分:0)
您应该使用urllib2.HTTPPasswordMgrWithDefaultRealm()
:
import urllib2
gh_url = 'https://api.github.com'
req = urllib2.Request(gh_url)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, 'user', 'pass')
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)
urllib2.install_opener(opener)
handler = urllib2.urlopen(req)
这是考虑使用requests
库的一种方式 - 它更容易:
import requests
r = requests.get('https://api.github.com', auth=('user', 'pass'))