python requests data和json参数的区别

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

datajson既可以是str类型,也可以是dict类型。

区别:

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

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

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

4、json为dict时,如果不指定content-type,默认为application/json

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

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

>>> r = requests.post('http://httpbin.org/post', json = {'key':'value'})
>>> r.json()
{'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '16', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ecc83a5-6972ba8590410bc2c36d42df'}, 'json': {'key': 'value'}, 'origin': '61.148.199.18', 'url': 'http://httpbin.org/post'}
>>> r = requests.post('http://httpbin.org/post', json = json.dumps({'key':'value'}))
>>> r.json()
{'args': {}, 'data': '"{\\"key\\": \\"value\\"}"', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '22', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ecc83b3-fd9620d07da4d72c64bb8b04'}, 'json': '{"key": "value"}', 'origin': '61.148.199.18', 'url': 'http://httpbin.org/post'}
>>> r = requests.post('http://httpbin.org/post', data = json.dumps({'key':'value'}))
>>> r.json()
{'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '16', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ecc83c1-c5d88e82526fc52b94a51f00'}, 'json': {'key': 'value'}, 'origin': '61.148.199.18', 'url': 'http://httpbin.org/post'}
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
>>> r.json()
{'args': {}, 'data': '', 'files': {}, 'form': {'key': 'value'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '9', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ecc83d0-09f85bff232d89cec4e5bdfb'}, 'json': None, 'origin': '61.148.199.18', 'url': 'http://httpbin.org/post'}

  

猜你喜欢

转载自www.cnblogs.com/hchan/p/12964131.html