python接口测试(post,get)-传参(data和json之间的区别)

python接口测试如何正确传参:

POST

传data:data是python字典格式;传参data=json.dumps(data)是字符串类型传参

#!/usr/bin/env python3
# -*-coding:utf-8-*-
# __author__: hunter

import requests
import json

url = "http://xxxxxxxxxxxx/oauth/token"

data = {
        "clientId": "xxxxxxxxxxx",
        "password": "123456",
        "userName": "admin",
        "VerificationCode": "",
        "VerificationCodeKey": "f7dc3967-bfbc-4a0f-9e2d-4d6e403d10a1"
}

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

传json:data是python中字典类型;传参json=data是json类型

#!/usr/bin/env python3
# -*-coding:utf-8-*-
# __author__: hunter

import requests
import json

url = "http://xxxxxxxxx/oauth/token"

data = {
        "clientId": "xxxxxxxx",
        "password": "123456",
        "userName": "admin",
        "VerificationCode": "",
        "VerificationCodeKey": "f7dc3967-bfbc-4a0f-9e2d-4d6e403d10a1"
}

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

通过截图可以看出post传参的形式

 

 从源码可以看出来,data和json传参既可以是str也可以是dict,

data和json的区别:

1、不管jsonstr还是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}'的这种形式

get

传params

url = 'http://www.kuaidi100.com/query'


data = {"type": "shentong",
        "postid": "77300421263133"}

r = requests.get(url, params=data)
print(r.json())
原文地址:https://www.cnblogs.com/hemingwei/p/11580641.html