Python Requests.post() 方法用于将 HTTP POST 请求发送到指定的 URL。它允许将数据发送到通常用于提交表单或上传文件的服务器。
此方法接受 'url'、'data'、'json'、'headers'、'cookies'、'files' 和 'timeout' 等参数。使用 'data' 或 'json' ,它分别发送表单数据或 JSON 有效负载,其中 'headers' 可用于发送自定义 HTTP 标头,'files' 可用于上传文件。
它通过促进与 Web 服务的交互,返回一个包含状态代码、标头和内容等详细信息的响应对象。
语法
以下是 Python Requests.post() 方法的语法和参数 -
参数
以下是 Python 请求 post() 方法的参数 -
- url:请求发送到的 URL。
- data:请求的正文。这可以是字典、字节或要在请求正文中发送的类文件对象。
- JSON:要在请求正文中发送的 JSON 数据。
- headers:与请求一起发送的 HTTP 标头。
- files:要与请求一起上传的文件。
- auth:Auth 元组,用于启用 Basic/Digest/Custom HTTP Auth 或自定义身份验证可调用对象。
- cookies:与请求一起发送的 Cookie。
- timeout:请求的超时。
- allow_redirects:确定是否应遵循重定向。
- proxies:将协议映射到代理 URL 的字典。
- verify:控制是否启用 SSL 证书验证。
返回值
此方法返回 Response 对象。
示例 1
以下是使用 python Requests.post() 方法将包含表单数据的简单 POST 请求发送到指定 URL 的基本示例 -
输出
Status Code: 200
Response Content: {
"args": {},
-------------
------------
------------
"json": null,
"origin": "110.226.149.205",
"url": "https://httpbin.org/post"
}
Response Content: {
"args": {},
-------------
------------
------------
"json": null,
"origin": "110.226.149.205",
"url": "https://httpbin.org/post"
}
示例 2
服务器将收到包含提供的 JSON 数据的 POST 请求,并打印来自服务器的响应,包括状态代码和任何响应内容。这是它的示例 -
输出
Status Code: 200
Response Content: {
"args": {},
"data": "{\"key1\": \"value1\", \"key2\": \"value2\"}",
-------------
------------
------------
"json": {
"key1": "value1",
"key2": "value2"
},
"origin": "110.226.149.205",
"url": "https://httpbin.org/post"
}
Response Content: {
"args": {},
"data": "{\"key1\": \"value1\", \"key2\": \"value2\"}",
-------------
------------
------------
"json": {
"key1": "value1",
"key2": "value2"
},
"origin": "110.226.149.205",
"url": "https://httpbin.org/post"
}
示例 3
以下是使用 Python 中 requests 模块 post() 方法的超时 POST 请求示例 -
输出
Status Code: 200
Response Content: {
"args": {},
"data": "{\"key1\": \"value1\", \"key2\": \"value2\"}",
-------------
------------
------------
},
"origin": "110.226.149.205",
"url": "https://httpbin.org/post"
}
Response Content: {
"args": {},
"data": "{\"key1\": \"value1\", \"key2\": \"value2\"}",
-------------
------------
------------
},
"origin": "110.226.149.205",
"url": "https://httpbin.org/post"
}