请求 - SSL 认证


SSL 证书是一种安全功能,附带安全 URL。当您使用 Requests 库时,它还会验证给定 https URL 的 SSL 证书。默认情况下,请求模块中启用 SSL 验证,如果证书不存在,则会抛出错误。

使用安全 URL

以下是使用安全 URL 的示例 -

import requests
getdata = requests.get(https://jsonplaceholder.typicode.com/users)
print(getdata.text) 

输出

E:\prequests>python makeRequest.py
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "Sincere@april.biz",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
]

我们很容易从上面的 https URL 得到响应,这是因为请求模块可以验证 SSL 证书。

您只需添加 verify=False 即可禁用 SSL 验证,如下例所示。

例子

import requests
getdata = 
requests.get('https://jsonplaceholder.typicode.com/users', verify=False)
print(getdata.text)

您将得到输出,但它也会给出一条警告消息,表明 SSL 证书未经过验证,建议添加证书验证。

输出

E:\prequests>python makeRequest.py
connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is 
being made. Adding certificate verification is strongly advised. See: 
https://urllib3
.readthedocs.io/en/latest/advanced-usage.htm  l#ssl-warnings
 InsecureRequestWarning)
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret", 
      "email": "Sincere@april.biz",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered   client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
]

您还可以通过将 SSL 证书托管在您的一端来验证 SSL 证书,并使用验证参数提供路径,如下所示。

例子

import requests
getdata = 
requests.get('https://jsonplaceholder.typicode.com/users', verify='C:\Users\AppData\Local\certificate.txt')
print(getdata.text)  

输出

E:\prequests>python makeRequest.py
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "Sincere@april.biz",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered   client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
]