python requests post加速_python接口自动化测试-requests.post()

表单参数提交:

Content-Type:application/x-www-form-urlencoded

内容:key1=value1&key2=value2

requests.post(url,data={'key1':'value1','key2':'value2'})

json参数提交:

Content-Type:application/json

内容:'{"key1":"value1","key2":"value2"}'

requests.post(url,json={'key1':'value1','key2':'value2'})

常用返回信息:

post方法简单使用:

1、带数据的post

importrequests

url= "https://xxx.com.cn/mcn/android/7.4.1/listWatcher"

#headers = {"Content-Type":"application/json",#"charset":"UTF-8"}

data ={"device": "5","deviceId": "ffffffff-f25a-774e-ffff-ffffef05ac4a","deviceType": 1,"ip": "192.168.129.46","pageIndex": 1,"pageSize": 10,"session": "f23a05a446284538b9c170bdee3035e58b","sessionId": "f23a05a446284538b9c170bdee3035e58b","version": "7.4.1"}

r= requests.post(url = url,json =data)print(r.json())

requests.post方法中data与json参数区别

在通过requests.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json。

data与json既可以是str类型,也可以是dict类型。

区别:

1、不管json是str还是dict,如果不指定headers中的content-type,默认为application/json

2、data为dict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式

此时数据可以从request.POST里面获取,而request.body的内容则为a=1&b=2的这种形式,注意,即使指定content-type=application/json,request.body的值也是类似于a=1&b=2,所以并不能用json.loads(request.body.decode())得到想要的值

3、data为str时,如果不指定content-type,默认为application/json

4、用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式

importrequestsimportjson

url= "https://mcn-app-t1.daydaycook.com.cn/mcn/android/7.4.1/listWatcher"headers= {"Content-Type":"application/json"}

data={"device": "5","deviceId": "ffffffff-f25a-774e-ffff-ffffef05ac4a","deviceType": 1,"ip": "192.168.129.46","pageIndex": 1,"pageSize": 10,"session": "f23a05a446284538b9c170bdee3035e58b","sessionId": "f23a05a446284538b9c170bdee3035e58b","version": "7.4.1"}

data= json.dumps(data) #在python中json格式的数据实际上就是一个字符串,json.dumps()是str类型#对于可以作为json.loads()参数对象的字符串,除了要满足字典类型的格式外,所有的字符串对象必须是双引号,转化后是dict类型

r = requests.post(url = url,data = data,headers =headers)print(r.json())

对于python字典和json虽然长得一样,但是数据序列化格式还是有一定的区别