在通過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表單提交的形式
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'}