Python Requests POST 请求使用 Content-Type: application/json
如果您想使用 Python 的 requests 库发送一个 POST 请求,并且需要使用 Content-Type 为 'application/json',请按照以下步骤操作:
- 导入 requests 库
import requests
- 准备请求参数
您需要准备一个字典,其中包含您希望发送的 JSON 数据。例如:
payload = {'key1': 'value1', 'key2': 'value2'}
- 发送 POST 请求
使用 requests 库发送 POST 请求,并将 Content-Type 设置为 'application/json'。例如:
headers = {'Content-Type': 'application/json'}
response = requests.post(url, json=payload, headers=headers)
其中,url 是您要发送请求的 URL 地址。
- 处理响应结果
您可以使用 response 对象来处理响应结果。例如:
print(response.status_code)
print(response.text)
其中,status_code 是 HTTP 响应状态码,text 是响应内容的字符串形式。
总的来说,以下是一个完整的示例代码:
import requests
url = 'https://example.com/api'
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, json=payload, headers=headers)
print(response.status_code)
print(response.text)
原文地址: https://www.cveoy.top/t/topic/orVn 著作权归作者所有。请勿转载和采集!