在发出Python POST请求之前,我们是否需要进行json.dumps和编码?

在发出Python POST请求之前,我们是否需要进行json.dumps和编码?,python,json,python-3.x,python-requests,Python,Json,Python 3.x,Python Requests,问题1)在发出Python POST请求之前,我们需要进行json.dumps和编码吗 通常要求是: response = requests.post('https://httpbin.org/post', json={'key':'value'}) 问题2) 这样做是否明智 x1 = {'key':'value'} x2 = json.dumps(x1) x3 = x2.encode() response = requests.post('https://httpbin.org/post',

问题1)在发出Python POST请求之前,我们需要进行json.dumps和编码吗

通常要求是:

response = requests.post('https://httpbin.org/post', json={'key':'value'})
问题2)

这样做是否明智

x1 = {'key':'value'}
x2 = json.dumps(x1)
x3 = x2.encode()
response = requests.post('https://httpbin.org/post', json=x3)

问题3)在发出Python POST请求之前,我们什么时候需要进行json.dumps和编码?

否,如果使用
json
参数,它应该是一个字典。发件人:

json–(可选)要在请求体中发送的json可序列化Python对象


您只需在发出post请求之前使用转储数据,如下所示-

url = "http://localhost:8080"
obj = {'City': 'Delhi', 'Country': 'India', 'message': 'Hello Team!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
requests.post(url, data=json.dumps(obj), headers=headers)

注意:我在测试期间观察到的转储在POST请求中是不必要的。它还应仅适用于
data=obj

您可以在
response=requests.post中以
data
参数的形式传递数据https://httpbin.org/post“,data={'key':“value”})
您还可以在header参数中将适当的内容类型设置为dictionary