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'}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM