post请求中,可以使用data传递参数,也可以使用json传递参数,那么这两种方式有什么区别呢?
如果参数为JSON数据,可以直接传入json参数,它将自动编码并将Content-Type的置为application/json
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("https://httpbin.org/post", json=payload)
print(r.text)
如果data传递的参数为字符串,例如【json.dumps(payload)】,则request对参数进行url编码,Content-Type的值为None,所以data传字符串时,一定要在header中指定Content-Type
payload = {'key1': 'value1', 'key2': 'value2'}
headers={"Content-Type": "application/json"}
r = requests.post("https://httpbin.org/post", headers=headers,data=json.dumps(payload))
print(r.text)
如果data传递的是字典、元组组成的列表或列表作为值的字典,则request对参数进行url编码,Content-Type的值为application/x-www-form-urlencoded
# 字典
payload1 = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("https://httpbin.org/post", data=payload1)
# 元组组成的列表
payload2 = [('key1', 'value1'), ('key1', 'value2')]
r = requests.post("https://httpbin.org/post", data=payload2)
# 列表作为值的字典
payload3 = {'key1': ['value1', 'value2']}
r = requests.post("https://httpbin.org/post", data=payload3)
|