python requests post参数的异同

python requests包在post数据时根据data参数的不同,所发送的数据格式也不同,例如在request.post(url,data=)这里就有如下几种方式

  • requests.post(url,json = data)除了可以自行对 dict 进行编码,你还可以使用 json 参数直接传递,然后它就会被自动编码。这是 2.4.2 版的新加功能
  • requests.post(url,data = json.dumps(data))
  • requests.post(url,data = data)

为了便于记忆这里实验记录一下,实验通过nc命令监听端口,查看接收到的原始数据,按照如上顺序分别实验发送数据+接收到的数据

1
2
3
4
5
data = {
'key':['123-+%/','456e":']
}
requests.post(url,json = data)
#json
1
2
3
4
5
6
7
8
9
10
11
12
13
#json
nc -l 11111
POST /api/v3/user/keys HTTP/1.1
Host: 127.0.0.1:11111
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.13.0
PRIVATE-TOKEN: okLuMsU7y1dPukxHDzrq
Content-Length: 31
Content-Type: application/json

{"key": ["123-+%/", "456e\":"]}

1
2
3
4
5
data = {
'key':['123-+%/','456e":']
}
requests.post(url,data = json.dumps(data))
#data=json.dump
1
2
3
4
5
6
7
8
9
10
POST /api/v3/user/keys HTTP/1.1
Host: 127.0.0.1:11111
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.13.0
PRIVATE-TOKEN: okLuMsU7y1dPukxHDzrq
Content-Length: 31

{"key": ["123-+%/", "456e\":"]}

1
2
3
4
5
data = {
'key':['123-+%/','456e":']
}
requests.post(url,data = json.dumps(data))
#data={}
1
2
3
4
5
6
7
8
9
10
11
POST /api/v3/user/keys HTTP/1.1
Host: 127.0.0.1:11111
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.13.0
PRIVATE-TOKEN: okLuMsU7y1dPukxHDzrq
Content-Length: 32
Content-Type: application/x-www-form-urlencoded

key=123-%2B%25%2F&key=456e%22%3A

通过如上实验可以发现,使用json={}和data = json.dumps()的效果是一样的,区别仅仅在于有无Content-Type:application/json,而使用data = {}这种形式发送的数据是表单形式,后面有机会再详细研究一下json和www-form方式的区别:)

转载请注明来源链接 http://just4fun.im/2017/10/19/python-requests-post参数的异同/ 尊重知识,谢谢:)