下面是一个使用urllib2的简单示例,它针对GitHub的API执行基本身份验证。import urllib2
u='username'
p='userpass'
url='https://api.github.com/users/username'
# simple wrapper function to encode the username & pass
def encodeUserData(user, password):
return "Basic " + (user + ":" + password).encode("base64").rstrip()
# create the request object and set some headers
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/x-www-form-urlencoded")
req.add_header('Authorization', encodeUserData(u, p))
# make the request and print the results
res = urllib2.urlopen(req)
print res.read()
此外,如果将其包装在脚本中并从终端运行,则可以将响应字符串管道化到“mjson.tool”以启用漂亮的打印。>> basicAuth.py | python -mjson.tool
最后要注意的是,urllib2只支持GET&POST请求。
如果您需要使用其他HTTP动词,如DELETE、PUT等,您可能需要查看PYCURL