在Python中,您可以使用requests库来处理JSON数据,而不是使用cURL命令。首先,确保您已经安装了requests库。如果没有,可以通过以下命令安装:
pip install requests 然后,您可以使用以下代码来发送一个包含JSON数据的POST请求:
import requests import json url = "https://example.com/api/endpoint" data = { "key1": "value1", "key2": "value2" } headers = { "Content-Type": "application/json" } response = requests.post(url, data=json.dumps(data), headers=headers) if response.status_code == 200: json_data = response.json() print("Success:", json_data) else: print("Error:", response.status_code, response.text) 在这个例子中,我们首先导入requests和json库。然后,我们定义要发送数据的URL和要发送的数据。接下来,我们设置请求头,指定内容类型为JSON。最后,我们使用requests.post()方法发送POST请求,并将数据和请求头作为参数传递。
如果请求成功(状态码为200),我们将响应内容解析为JSON格式,并打印成功消息和JSON数据。如果请求失败,我们打印错误状态码和响应文本。