python 发送post请求、请求体中设置json
Python发送POST请求,并在请求体中设置JSON数据,可以使用requests库。
示例代码如下:
import requests
url = 'https://example.com/api'
headers = {'Content-Type': 'application/json'}
data = {'name': 'John', 'age': 30}
response = requests.post(url, headers=headers, json=data)
print(response.text)
上面的代码中,我们先定义了请求的URL和请求头。然后我们定义了一个JSON数据,这里是一个字典。最后,我们使用requests.post()方法发送POST请求,并使用json参数指定请求体。
注意,我们设置了Content-Type请求头为application/json,这告诉服务器请求体是JSON格式的数据。
如果服务器返回的是JSON格式的响应,我们可以使用response.json()方法将响应转换为Python对象。如果服务器返回的是其他格式的响应,可以使用response.text获取响应内容。
原文地址: https://www.cveoy.top/t/topic/nAl 著作权归作者所有。请勿转载和采集!