13.Requests【接口请求】requests模拟发送https请求

一、前言

HTTP协议传输的数据都是未加密的,也就是明文的,因此使用HTTP协议传输隐私信息非常不安全,为了保证这些隐私数据能加密传输,于是网景公司设计了SSL(Secure Sockets Layer)协议用于对HTTP协议传输的数据进行加密,从而就诞生了HTTPS。简单来说,HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议,要比http协议安全。

翻译成人话就是https请求比http安全,发送https请求,必须关闭SSL验证(SSL:安全套接字层。是为了解决HTTP协议是明文,避免传输的数据被窃取,篡改,劫持等。)

二、学习目标

1.【发送https请求】

三、知识点

1.【发送https请求】

注:当请求https接口时,会报如下错误:

ValueError: check_hostname needs a SSL context with either CERT_OPTIONAL or CERT_REQUIRED

这是由于urllib3版本太高导致的,所以在模拟https请求前,需要降低urllib3:

pip install urllib3==1.25.11 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

代码示例:

import requests

url_mul = 'https://www.httpbin.org/get'
res = requests.get(url_mul,verify=False)  #通过verify关闭ssl认证
print(res.text)

执行代码,我们发现,将验证设置忽略后,可以跳过SSL验证,但存在一个警告信息InsecureRequestWarning:

InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning,

【最终版】消除警告:

get:

import requests
import urllib3
#消除警告
from urllib3.exceptions import InsecureRequestWarning

urllib3.disable_warnings(InsecureRequestWarning)
url_mul = 'https://www.httpbin.org/get'
res = requests.get(url_mul,verify=False)
print(res.text)

post:

import requests
import urllib3
#消除警告
from urllib3.exceptions import InsecureRequestWarning

urllib3.disable_warnings(InsecureRequestWarning)
url_mul = 'https://www.httpbin.org/post'
res = requests.post(url_mul,verify=False)
print(res.text)
posted @ 2023-01-17 10:15  测开星辰  阅读(623)  评论(0编辑  收藏  举报