您需要设置内容类型标头:
data = {"data" : "24.3"}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}
response = requests.post(url, data=data_json, headers=headers)
如果我设置url
为http://httpbin.org/post
,该服务器会向我回显发布的内容:
>>> import json
>>> import requests
>>> import pprint
>>> url = 'http://httpbin.org/post'
>>> data = {"data" : "24.3"}
>>> data_json = json.dumps(data)
>>> headers = {'Content-type': 'application/json'}
>>> response = requests.post(url, data=data_json, headers=headers)
>>> pprint.pprint(response.json())
{u'args': {},
u'data': u'{"data": "24.3"}',
u'files': {},
u'form': {},
u'headers': {u'Accept': u'*/*',
u'Accept-Encoding': u'gzip, deflate, compress',
u'Connection': u'keep-alive',
u'Content-Length': u'16',
u'Content-Type': u'application/json',
u'Host': u'httpbin.org',
u'User-Agent': u'python-requests/1.0.3 CPython/2.6.8 Darwin/11.4.2'},
u'json': {u'data': u'24.3'},
u'origin': u'109.247.40.35',
u'url': u'http://httpbin.org/post'}
>>> pprint.pprint(response.json()['json'])
{u'data': u'24.3'}
如果您使用的是requests
2.4.2 或更高版本,则可以将 JSON 编码留给库;它也会自动为您设置正确的 Content-Type 标头。将要作为 JSON 发送的数据传入json
关键字参数:
data = {"data" : "24.3"}
response = requests.post(url, json=data)