我有curl命令,我需要转移到Python中请求POST
curl -X POST -H "Content-Type: application/json" -d '{"val1": -1000, "val2": 15, "val3": "20000", "val4": "22"}'
http://some-site:6000?t=1234567890
我尝试过:
payload = {'val1': val1, 'val2': val2, 'val3': val3, 'val4': val4}
r = requests.post(url, params=payload)
r.url
返回:
http://some-site:6000?t=1234567890&val1=-1000&val2=15&val3=20000&val4=22
但是,我从服务器得到val1 is not defined
响应。我可以在curl命令中看到val1和val2是int类型。我可以单独发送requests
整数和字符串,或者这不是导致此错误的原因吗?
答案 0 :(得分:4)
您是否尝试requests.post(url, json=payload)
?params=payload
追加查询字符串参数,json=payload
发送JSON作为正文+内容类型标题
import requests
payload = {'val1': 1, 'val2': 2, 'val3': 3, 'val4': 3}
r = requests.post('http://httpbin.org/post', json=payload)
print(r.json())
>>> {u'args': {},
>>> u'data': u'{"val3": 3, "val2": 2, "val1": 1, "val4": 3}',
>>> ...