requests.post()方法
源碼如下:
def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs)
可以看到,參數(shù)中明確的參數(shù)有data與json
data與json既可以是str,也可以是dict
區(qū)別如下:
- 不管
json是str還是dict,如果不指定headers中的content-type,默認(rèn)為application/json -
data為dict時(shí),如果不指定content-type,默認(rèn)為application/x-www-form-urlencoded,相當(dāng)于普通form表單提交的形式,此時(shí)數(shù)據(jù)可以從request.POST里面獲取,而request.body的內(nèi)容則為a=1&b=2的這種形式,注意,即使指定content-type=application/json,request.body的值也是類似于a=1&b=2,所以并不能用json.loads(request.body.decode())得到想要的值 -
data為str時(shí),如果不指定content-type,默認(rèn)為application/json
content-type=application/json下,獲取值的方法如下:
json.loads(request.body.decode())