requests模块中post方法的定义如下
>>> help(requests.post)
Help on function post in module requests.api:
post(url, data=None, json=None, **kwargs)
Sends aPOST request.
:paramurl: URL for the new :class:`Request` object.
:paramdata: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:paramjson: (optional) json data to send in the body of the :class:`Request`.
:param\*\*kwargs: Optional arguments that ``request`` takes.
:return::class:`Response ` object
:rtype:requests.Response
>>>
常见请求体格式有
普通字典格式
想要发送一些表单形式的数据,只需简单的传递一个字典格式给data关键字参数,在发送请求的时候,会自动编码为表单的形式。
url=http://10.10.1.65:8080/api/3.0/W/login
payload={
"params": '{"userName":"18810756676","password":"e10adc394=ba*9abbe56e057f20f883e","ip":"","tagCode":"INVEST"}',
"from": "W",
"imei": "imei"
}
r=requests.post(url,data=payload,verify=False)
在charles代理上看请求信息如下
POST/api/3.0/W/login HTTP/1.1
Host:10.10.1.65:8080
Connection:keep-alive
Accept-Encoding:gzip, deflate
Accept:*/*
User-Agent:python-requests/2.19.1
Content-Type:application/x-www-form-urlencoded
Content-Length:173
imei=imei&from=W¶ms=%7B%22userName%22%3A%2218810756676%22%2C%22password%22%3A%22e10adc3949ba59abbe56e057f20f883e%22%2C%22ip%22%3A%22%22%2C%22tagCode%22%3A%22INVEST%22%7D
Json格式字符串
在很多情况下,想要发送的数据并非为表单形式,而是一个json格式的字符串(如发送的body体格式为application/json),因此为了将一个数据结构(python对象)转换为json格式的字符串,首先得需要导入一个json包,使用json.dumps()将其转化为json编码的字符串,那么数据会被直接发送出去,不会自动编码为表单形式。
json编码支持的python基本类型有:None, bool, int, float, string, list, tuple, dict。要符合JSON格式规范,应该只对python列表和字典进行编码。对于字典,json会假设key是字符串(字典中的任何非字符串key都会在编 码时转换为字符串)。
如
BASE_URL=http://10.255.255.93:8081/anifratud/aqpi/grdandorders
payload= {"custId": 502632248,"grandOrderId":376533235355209,"totalBarginPrice": 20450300}
headers= {
'Content-Type':"application/json",
'Cache-Control':"no-cache",}
load=json.dumps(payload)
r=requests.request("POST",BASE_URL, data=load, headers=headers)