问题描述
我正在尝试使用python将xml发布到站点.我必须附上证书,但不确定如何执行此操作.在我的计算机上本地指定证书的文件路径是否足够?
I am trying to POST xml to a site using python. I have to include a certificate but am unsure of how to do this. Is it enough to specify the file path of the certificate locally on my computer?
任何人都可以向我展示如何在请求中包括证书的示例吗?
Can anybody show my an example of how to include the certificate in the request?
import http.client, urllib.parse
xml="""<?xml version="1.0" encoding="UTF-8"?>
<home>
<bathroom>1</bathroom>
<kitchen>1</kitchen>
<street>515</street>
</home>);"""
headers = {"username": "password"}
conn = http.client.HTTPSConnection("someurl.com", cert_file="D:\Users\Username\certificate.p12")
conn.request("POST", "/to/this/place", xml, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)
conn.close()
推荐答案
如果您不使用自签名证书,并且您的证书是由相对可靠的权威机构(即互联网上正常的someurl.com)签名的,则建立连接时,应使用系统CA证书.
If you aren't using self-signed certs and your cert is signed by a relatively trustworthy authority (i.e. to a normal someurl.com on the internet) then you should use the system CA certificates when making your connection.
您可以仅通过调用HTTPSConnection()来执行此操作,而无需在Python 3.4.3或更高版本中为其提供证书文件或上下文.
You can do that by just invoking the HTTPSConnection() without giving it a cert file or context in Python 3.4.3 or greater.
如果您使用的是自签名证书,则可以从本地硬盘驱动器加载证书.您需要将私钥包含在证书文件中或指定为密钥文件.如果您的环境中完全有可能,您还将希望进行主机验证.请参见verify_mode
和check_hostname
选项.
If you are using self-signed certificates then yes you can load the certs from the local hard drive. You will need to have the private key included in the certificate file or specified as the key file. You will also want to do host verification if it is at all possible in your environment. See the verify_mode
and check_hostname
options.
import http.client
import ssl
password = input("Key password (enter for none):") or None
xml = """<?xml version="1.0" encoding="UTF-8"?>
<home>
<bathroom>1</bathroom>
<kitchen>1</kitchen>
<street>515</street>
</home>);"""
headers = {"username": "password"}
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.load_cert_chain("cert.pem", "key.pem", password=password)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
conn = http.client.HTTPSConnection("someurl.com", port=443, context=context)
conn.request("POST", "/to/this/place")
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data)
conn.close()
这篇关于使用python和http.client在发布请求中包含证书的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!