📜  Python请求——带有标题和正文的 POST 请求(1)

📅  最后修改于: 2023-12-03 14:46:47.729000             🧑  作者: Mango

Python请求——带有标题和正文的 POST 请求

在使用 Python 进行请求时,常常会需要发送一个 POST 请求,该请求需要包含标题和正文,下面介绍如何使用 Python 发送带有标题和正文的 POST 请求。

准备工作

首先需要导入需要的库:

import requests
发送请求

使用 requests 库发送请求需要使用 requests.post() 方法,该方法的第一个参数是请求的 URL,第二个参数是请求数据,以字典形式传递。可以通过 headers 参数传递标题信息。

例如,向 https://example.com/ 发送 POST 请求,数据为 { "key": "value" },标题为 "title",代码如下:

url = "https://example.com/"
data = { "key": "value" }
headers = { "title": "title" }

response = requests.post(url, data=data, headers=headers)
处理响应

发送请求后需要处理响应,可以通过 response 对象获取响应的状态码、正文和标题等信息。

例如,获取响应的状态码和正文,代码如下:

status_code = response.status_code
content = response.content.decode()
完整示例

下面是完整示例:

import requests

url = "https://example.com/"
data = { "key": "value" }
headers = { "title": "title" }

response = requests.post(url, data=data, headers=headers)

status_code = response.status_code
content = response.content.decode()

print(f"Status code: {status_code}")
print(f"Content: {content}")

以上就是使用 Python 发送带有标题和正文的 POST 请求的完整介绍。