Python 使用requests发送POST请求
2018-01-30 17:10
866 查看
15:10:04
37807
一个http请求包括三个部分,为别为请求行,请求报头,消息主体,类似以下这样:
请求行
请求报头
消息主体
HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式。服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析。具体的编码方式包括:
application/x-www-form-urlencoded
最常见post提交数据的方式,以form表单形式提交数据。
application/json
以json串提交数据。
multipart/form-data
一般使用来上传文件。
2.7.1 以form形式发送post请求
Reqeusts支持以form表单形式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可。
url = 'http://httpbin.org/post' d = {'key1': 'value1', 'key2': 'value2'} r = requests.post(url, data=d) print r.text
1
2
3
4
1
2
3
4
输出:
{
“args”: {},
“data”: “”,
“files”: {},
“form”: {
“key1”: “value1”,
“key2”: “value2”
},
“headers”: {
……
“Content-Type”: “application/x-www-form-urlencoded”,
……
},
“json”: null,
……
}
可以看到,请求头中的Content-Type字段已设置为application/x-www-form-urlencoded,且
d = {'key1': 'value1', 'key2': 'value2'}以form表单的形式提交到服务端,服务端返回的form字段即是提交的数据。
2.7.2 以json形式发送post请求
可以将一json串传给requests.post()的data参数,url = 'http://httpbin.org/post' s = json.dumps({'key1': 'value1', 'key2': 'value2'}) r = requests.post(url, data=s) print r.text
1
2
3
4
1
2
3
4
输出:
{
“args”: {},
“data”: “{\”key2\”: \”value2\”, \”key1\”: \”value1\”}”,
“files”: {},
“form”: {},
“headers”: {
……
“Content-Type”: “application/json”,
……
},
“json”: {
“key1”: “value1”,
“key2”: “value2”
},
……
}
可以看到,请求头的Content-Type设置为application/json,并将
s这个json串提交到服务端中。
2.7.3 以multipart形式发送post请求
Requests也支持以multipart形式发送post请求,只需将一文件传给requests.post()的files参数即可。
url = 'http://httpbin.org/post' files = {'file': open('report.txt', 'rb')} r = requests.post(url, files=files) print r.text
1
2
3
4
1
2
3
4
输出:
{
“args”: {},
“data”: “”,
“files”: {
“file”: “Hello world!”
},
“form”: {},
“headers”: {……
“Content-Type”: “multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”,
……
},
“json”: null,
……
}
相关文章推荐
- Python 使用requests发送POST请求
- Python使用requests发送POST请求实例代码
- python学习笔记:使用requests库发送get与post请求
- python 使用requests 实现 post 和get请求
- 使用python发送一个POST请求
- python+requests实现接口测试 - get与post请求使用( params
- 使用python的requests 发送multipart/form-data 请求
- 使用python的requests 发送multipart/form-data 请求
- Python requests发送post请求的一些疑点
- Python 使用requests模块发送GET和POST请求的实现代码
- python+requests实现接口测试 - get与post请求使用
- Python 使用requests模块发送GET和POST请求的实现代码
- Python -- 使用requests模块发送GET和POST请求
- python使用scrapy发送post请求的坑
- Python中通过requests模块发送POST请求.
- 使用python 处理发送POST请求
- 使用Python发送http post请求上传文件
- python中使用requests 模拟浏览器发送请求数据
- Http学习之使用HttpURLConnection发送post和get请求
- Http学习之使用HttpURLConnection发送post请求深入