接口测试-POST请求(七)

一、简介

学习requests模块,是让大家去访问官方网站,查看官方文档;其实学习一个新的模块捷径,不用去百度什么的,直接用 help 函数就能查看相关注释和案例内容。

print(help(requests))

  

二、POST请求案例,数据为dict格式

url = 'http://httpbin.org/post'
datas = {'key1':'value1','key2':'value2'}

#dict参数请求
p=requests.post(url,data=datas)
print(p.text)
print(p.status_code)

  

三、POST请求案例,数据为json格式

注意这里需要把dict转换成json数据格式

json_data = json.dumps(datas)

  

post请求参考

url = 'http://httpbin.org/post'
datas = {'key1':'value1','key2':'value2'}

json_data = json.dumps(datas)
#json请求
p=requests.post(url,json=json_data)
print(p.text)
print(p.status_code)

  

四、添加请求头header

现在由于对接口安全性的要求,使得模拟登录越来越复杂,比上边介绍的基本内容要复杂很多。一般来说登陆只要涉及安全性方面考虑,那么登陆就会比较复杂。

1、以博客园为例,几年前模拟登陆,没有涉及安全性考虑相对简单。发展到现在其登录涉及安全性考虑,所以实际的情况要比上面讲的几个复杂很多,

2、我们在请求数据时也可以加上自定义的headers(通过headers关键字参数传递)有时候有的特殊的请求必须加上headers头信息,才回返回响应结果。例如:博客园登录时,将请求头 headers添加上,这里不是说博客园登录必须登录才能返回

响应结果,而是以其为例子来说明将请求头header参数加入到登录请求接口中

2.1 抓包,查看其请求头,或者浏览器F12,接口查看对应header

 

 

 

 参考代码:

url = 'http://httpbin.org/post'
datas = {'key1':'value1','key2':'value2'}
#header,以字典形式传入
headerst = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'}
json_data = json.dumps(datas)
#json请求
p=requests.post(url,headers=headerst,json=json_data)
print(p.text)
print(p.status_code)

  

 

遇到问题报错和解决办法:

报错:

raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /post (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

 解决办法:

1、由于这里是 https 请求,直接发送请求会报错误:SSLError: HTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /post (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

2、可以加个参数:verify=False,表示忽略对 SSL 证书的验证,但是此时仍然会有警告:

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

3、这里请求参数 payload 是 json 格式的,用 json 参数传。将请求头写成字典格式,进行传参。

4、最后结果是 json 格式,可以直接用 r.json 返回 json 数据:

{'args': {}, 'data': '', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '0', 'Host': 'httpbin.org', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'}, 'json': None, 'origin': '222.128.10.95, 222.128.10.95', 'url': 'https://httpbin.org/post'}

posted @ 2022-03-11 15:02  究极不吃香菜  阅读(804)  评论(0编辑  收藏  举报