本文介绍: 在Python中的requests库中,使用post()方法发送POST请求,如果需要传递JSON格式数据,则可以设置请求头Content-Type为”application/json“,并将数据通过json参数传递。

例如

import requests
import json

url = 'http://example.com/path/to/api'

data = {
    'name': 'John',
    'age': 30,
    'gender': 'male'
}

headers = {'Content-type': 'application/json'}

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

print(response.status_code)
print(response.json())

这里通过json参数传递了一个字典类型data数据,在请求头中设置Content-Typeapplication/jsonrequests自动json参数转化为合法的JSON格式,并且将其作为请求体提交服务器。注意,这里json参数是requests库中的内置参数之一,表示将请求体数据序列化为JSON格式

服务器端收到上述POST请求时,可以使用request对象json属性获取提交过来的JSON数据。

需要注意的是,如果要使用requests发送JSON类型的数据,就必须设置请求头Content-Type为”application/json”,否则服务端无法正确解析请求。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注