[975]python requests实现HTTPS客户端的证书导入
作者:互联网
最近需要测试一个HTTPS接口,基于CA证书、client key、 client 证书的ssl连接。
网上了解到的实现是用python+urllib,
import urllib.request
import ssl
if __name__ == '__main__':
CA_FILE = "ca.crt"
KEY_FILE = "client.key"
CERT_FILE = "client.crt"
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.check_hostname = False
context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
context.load_verify_locations(CA_FILE)
context.verify_mode = ssl.CERT_REQUIRED
try:
# 通过request()方法创建一个请求:
request = urllib.request.Request('https://127.0.0.1:5000/')
res = urllib.request.urlopen(request, context=context)
print(res.code)
print(res.read().decode("utf-8"))
except Exception as ex:
print("Found Error in auth phase:%s" % str(ex))
想用python+requests实现,但requests没有context参数,requests官网描述如下,
用requests的cert+verify参数实现,连接成功,代码如下:
import requests
import ssl
if __name__ == '__main__':
try:
# 通过request()方法创建一个请求:
r=requests.get("https://127.0.0.1:5000/",cert=('client.crt','client.key'),verify='ca.crt')
print(r.status_code)
print(r.text)
print(r.headers)
except Exception as ex:
print("Found Error in auth phase:%s" % str(ex))
来源:https://blog.csdn.net/weixin_51380973/article/details/113864819
标签:__,975,HTTPS,python,FILE,request,context,print,requests 来源: https://blog.csdn.net/xc_zhou/article/details/116769386