ValueError: check_hostname requires server_hostname
时间: 2023-10-23 19:07:56 浏览: 41
这个错误通常是由于使用了`ssl`库的`verify_mode`参数错误引起的。在使用`ssl`库进行加密通信时,`verify_mode`参数可以用来指定证书验证的方式。如果`verify_mode`参数设置为`CERT_REQUIRED`,则需要指定`server_hostname`参数来验证服务器的主机名。以下是一个示例代码,可以通过设置`server_hostname`参数来解决此错误:
```python
import ssl
import urllib.request
# 创建SSL上下文
context = ssl.create_default_context()
# 设置证书验证模式为CERT_REQUIRED,并指定服务器主机名
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
server_hostname = "www.example.com"
# 创建HTTPS请求并发送
url = "https://www.example.com/"
req = urllib.request.urlopen(url, context=context, timeout=5, server_hostname=server_hostname)
res = req.read()
print(res)
```
请注意,在此示例中,我们首先创建了一个默认的SSL上下文,并将`check_hostname`参数设置为`True`,`verify_mode`参数设置为`CERT_REQUIRED`。然后,我们指定了服务器的主机名,并将其传递给`urllib.request.urlopen()`函数的`server_hostname`参数。这样就可以解决`ValueError: check_hostname requires server_hostname`错误。