POST请求用于向服务器提交数据,比如提交一个表单新建一个用户、或修改一个用户信息等操作。
对于POST请求,我们可以通过浏览器开发者工具或者其他外部工具来进行抓包,得到请求的URL、请求头(request headers)以及请求的表单data信息,这三样恰恰是我们用Requests库模拟POST请求时需要的。
关于请求头的配置和GET请求是一样的,都是定义headers属性即可。
而关于POST请求提交的参数,是和GET请求是不一样的。
post请求四种传送正文方式:
- (1)请求正文是application/x-www-form-urlencoded。
- (2)请求正文是multipart/form-data。
- (3)请求正文是raw。
- (4)请求正文是binary。
这四种提交数据的方式,是在请求头Content-Type属性中来定义。
1、请求正文是application/x-www-form-urlencoded
Reqeusts支持以application/x-www-form-urlencoded数据格式发送POST请求(标准的POST请求数据格式,默认),只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可。
示例:
"""
1.学习目标
必须掌握requests库发送post请求方法
2.HTTP协议中post请求参数类型
requests.post(url, data=None, json=None, **kwargs)
根据不同的请求参数类型分为如下几种:
x-www-form-data-urlencoded
raw_json格式
form-data
binary
3.json格式
# 1.导入requests库
# 2.明确请求地址
# 3.明确请求参数
data = {key:value} 字典格式
# 4.发送请求
requests.post(url=url,json=data)
4.需求
通过访问http://httpbin.org/post接口,验证post参数类型"""
# 1.导入requests库
import requests
import json# 2.明确请求地址
url = "http://httpbin.org/post"
# 3.明确请求参数
data = {
"dep_id": "T01",
"dep_name": "Test学院",
"master_name": "Test-Master",
"slogan": "Here is Slogan"
}
# 4.发送请求
response = requests.post(url=url, data=data)# 将python对象转换为json字符串(格式化返回数据)
result = json.dumps(response.json(), indent=2, ensure_ascii=False)
# print(type(result)) # 字符串类型
print(result)"""
返回结果:
{
"args": {},
"data": "",
"files": {},
****************主要看这里
"form": {
"dep_id": "T01",
"dep_name": "Test学院",
"master_name": "Test-Master",
"slogan": "Here is Slogan"
},
***********************
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "88",
*****************主要看这里
"Content-Type": "application/x-www-form-urlencoded",
*****************
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4",
"X-Amzn-Trace-Id": "Root=1-5ff401e3-1553596b7788e77e275c4772"
},
"json": null,
"origin": "106.35.9.12",
"url": "http://httpbin.org/post"
}
"""
说明:
- 发送的请求中,form属性接收了参数。
- 在请求头中,Content-Type属性为application/x-www-form-urlencoded
- 使用application/x-www-form-urlencoded格式发送数据,requests.post(url=url,
- data=data)方法中一定要使用data变量来接收参数。
- 换句话说数据格式是字典格式,使用data变量来接收,会默认发送application/x-www-form-urlencoded数据格式的POST请求。(也可以在请求头中明确一下Content-Type属性,但没必要。)
2、请求正文是raw
RAW的原意就是“未经加工”。换句话说RAW方式使用的是纯字符串的数据上传方式,所以在发送POST请求之前,可能需要手工的把一些JSON格式的数据转换成字符串的(加两单引号),在进行提交。
RAW数据格式的POST请求有两种:
- 一种是xml格式文本(text/xml)。
- 一种是json格式文本(application/json)。
(1)json格式文本(application/json)
# 1.导入requests库
import requests
import json# 2.明确请求地址
url = "http://httpbin.org/post"
# 3.明确请求参数
data = {
"data": [
{
"dep_id": "T01",
"dep_name": "Test学院",
"master_name": "Test-Master",
"slogan": "Here is Slogan"
}
]
}# headers = {"Content-Type": "application/json"}
# 4.发送请求
response = requests.post(url=url, json=data)
print(response) # <Response [200]>
print(response.text)
"""
返回结果:
{
"args": {},
"data": "{\"data\": [{\"dep_id\": \"T01\", \"dep_name\": \"Test\\u5b66\\u9662\", \"master_name\": \"Test-Master\", \"slogan\": \"Here is Slogan\"}]}",
"files&#