Python,具有基本身份验证的 HTTPS GET

问题描述:

我正在尝试使用 python 进行基本身份验证的 HTTPS GET.我对 python 很陌生,指南似乎使用不同的库来做事.(http.client、httplib 和 urllib).谁能告诉我它是怎么做的?如何告诉标准库使用?

Im trying to do a HTTPS GET with basic authentication using python. Im very new to python and the guides seem to use diffrent librarys to do things. (http.client, httplib and urllib). Can anyone show me how its done? How can you tell the standard library to use?

在 Python 3 中,以下内容将起作用.我正在使用标准库中较低级别的 http.client.另请查看 rfc2617 的第 2 节了解基本授权的详细信息.此代码不会检查证书是否有效,但会设置 https 连接.请参阅 http.client 文档了解如何执行此操作.

In Python 3 the following will work. I am using the lower level http.client from the standard library. Also check out section 2 of rfc2617 for details of basic authorization. This code won't check the certificate is valid, but will set up a https connection. See the http.client docs on how to do that.

from http.client import HTTPSConnection
from base64 import b64encode
#This sets up the https connection
c = HTTPSConnection("www.google.com")
#we need to base 64 encode it 
#and then decode it to acsii as python 3 stores it as a byte string
userAndPass = b64encode(b"username:password").decode("ascii")
headers = { 'Authorization' : 'Basic %s' %  userAndPass }
#then connect
c.request('GET', '/', headers=headers)
#get the response back
res = c.getresponse()
# at this point you could check the status etc
# this gets the page text
data = res.read()