如何使用证书进行身份验证在python中进行GET调用

时间:2017-01-08 12:51:27

标签: python python-2.7 client-certificates

Python新手在这里!

我在c#中编写了以下代码,我想在python中实现相同的功能。

string serviceURL = "https://someurl";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceURL);
                request.Method = "GET";
                string path = @"C:\mycert.cer";
                X509Certificate Cert = X509Certificate.CreateFromCertFile(path);

                Logger.Error(path);

                request.ClientCertificates.Add(Cert);

                HttpWebResponse WebResp = request.GetResponse() as HttpWebResponse;

                var encoding = ASCIIEncoding.ASCII;
                string responseText;
                StreamReader reader = new System.IO.StreamReader(WebResp.GetResponseStream(), encoding);
                using (reader = new System.IO.StreamReader(WebResp.GetResponseStream(), encoding))
                {
                    responseText = reader.ReadToEnd();
                }

我在google上做了一些搜索,但找不到合适的例子。

1 个答案:

答案 0 :(得分:-1)

我建议查看[requests] [1]库 - 它非常方便和酷。

>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> print(r.status_code)
200
print(r.text)
# ..... here response body goes ...

您可以使用受信任CA的证书验证路径到CA_BUNDLE文件或目录:

>>> requests.get('https://github.com', verify='/path/to/certfile')