2017-01-08 39 views
0

Python新手在這裏!如何在Python中使用證書進行GET認證以進行身份​​驗證

我已經在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(); 
       } 

我在谷歌上做了一些搜索,但找不到任何合適的例子。

回答

0

我建議看[請求] [1]庫 - 它非常方便和酷。

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

你可以通過驗證的CA_BUNDLE文件或目錄與信任的CA證書的路徑:

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

當我用你的例子中,我得到這個錯誤。 「requests.exceptions.SSLError:未知錯誤(_ssl.c:2826)」 –

+0

你在哪個網址得到它? –

+0

這是一個內部公司URL –

相關問題