JSON 请求
在接口的请求中常常会碰到需要发送 json 格式的请求,这种情况下,既可以使用关键字参数 data,也可以使用关键字参数 json 来传递 json 请求。
JSON 请求的发送
使用 data 关键字发送 json 请求,需要使用 json.dumps 对传入的变量进行转码:
>>> import json
>>> import requests
>>> r = requests.post('http://httpbin.org/post', data=json.dumps({'key': 'value'}))
>>> print(r.request.headers)
{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate',\
'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '16'}
使用 json 关键字参数发送请求:
>>> import requests
>>> r = requests.post('http://httpbin.org/post', json = {'key':'value'})
>>> print(r.request.headers)
{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate',\
'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '16',\
'Content-Type': 'application/json'}
对比两次请求可以看出,如果请求的参数选择是 json

本文深入探讨接口测试中涉及的JSON请求和响应断言。讲解了使用data和json关键字发送JSON请求的区别,并重点介绍了JsonPath,包括其语法和与XPath的对比,以及如何使用JsonPath进行实战练习。同时,给出了Python结合JsonPath进行接口断言的实例。
最低0.47元/天 解锁文章
664

被折叠的 条评论
为什么被折叠?



