json
無論參數是str還是dict類型,如果不指定headers中的Content-Type,默認爲application/json
- 當參數爲
dict類型時,request.body中內容爲b'{"name":"zhubaoxiang"}'
當參數類型爲str時,request.body中內容爲b'"{\\"name\\":\\"zhubaoxiang\\"}"',可以看到,json默認會幫你json dumps一下。我們觀看requests源碼也得出相同結論:
def prepare_body(self, data, files, json=None):
"""Prepares the given HTTP body data."""
# Check if file, fo, generator, iterator.
# If not, run through normal process.
# Nottin' on you.
body = None
content_type = None
if not data and json is not None:
# urllib3 requires a bytes-like body. Python 2's json.dumps
# provides this natively, but Python 3 gives a Unicode string.
content_type = 'application/json'
body = complexjson.dumps(json)
if not isinstance(body, bytes):
body = body.encode('utf-8')
data
當參數
爲str類型時,Content-Type默認爲application/json,
request.body中內容爲
b'{"name":"zhubaoxiang"}'形式
當參數爲dict類型時,Content-Type默認爲application/x-www-form-urlencoded,即普通form表單形式,request.body中內容形式爲b'name=zhubaoxiang'。
- 值得注意點,當參數爲dict,即使指定Content-Type爲json,request.body中也是
b'name=zhubaoxiang'形式,不能直接json loads。