Python POST 请求 JSON 格式数据 - 使用 requests 模块
使用 Python 发送 POST 请求并以 JSON 格式传递数据,可以使用 requests 模块来完成。
以下示例代码展示了如何实现:
import requests
import json
url = 'http://example.com/api'
headers = {'Content-Type': 'application/json'}
data = {'username': 'john', 'password': 'doe'}
# 将 Python 对象转换为 JSON 字符串
json_data = json.dumps(data)
# 发送 POST 请求
response = requests.post(url, headers=headers, data=json_data)
# 解析响应数据
result = json.loads(response.text)
print(result)
在这个示例中,我们首先定义了一个 URL 和请求头部信息。然后,将 Python 对象转换为 JSON 字符串,并将其作为数据发送到服务器。最后,解析响应数据并打印出结果。
原文地址: https://www.cveoy.top/t/topic/ogdy 著作权归作者所有。请勿转载和采集!