使用Python请求发布JSON

我需要从客户端发送到服务器的JSON。 我正在使用Python 2.7.1和simplejson。 客户正在使用请求。 服务器是CherryPy。 我可以从服务器获取硬编码的JSON(代码未显示),但是当我尝试将JSON发布到服务器时,我得到“400错误请求”。

这是我的客户代码:

data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} data_json = simplejson.dumps(data) payload = {'json_payload': data_json} r = requests.post("http://localhost:8080", data=payload) 

这是服务器代码。

 class Root(object): def __init__(self, content): self.content = content print self.content # this works exposed = True def GET(self): cherrypy.response.headers['Content-Type'] = 'application/json' return simplejson.dumps(self.content) def POST(self): self.content = simplejson.loads(cherrypy.request.body.read()) 

有任何想法吗?

从请求版本2.4.2开始,您可以在调用中使用“json”参数,这使得它更简单。

 >>> import requests >>> r = requests.post('http://httpbin.org/post', json={"key": "value"}) >>> r.status_code 200 >>> r.json() {'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Content-Length': '16', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.4.3 CPython/3.4.0', 'X-Request-Id': 'xx-xx-xx'}, 'json': {'key': 'value'}, 'origin': 'xxxx', 'url': 'http://httpbin.org/post'} 

编辑:此function已添加到官方文档。 您可以在这里查看: 请求文档

原来我错过了标题信息。 以下工作:

 url = "http://localhost:8080" data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(data), headers=headers) 

从请求2.4.2( https://pypi.python.org/pypi/requests ),支持“json”参数。 不需要指定“Content-Type”。 所以较短的版本:

 requests.post('http://httpbin.org/post', json={'test': 'cheers'}) 

与python 3.5+完美合作

客户:

 import requests data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} r = requests.post("http://localhost:8080", json={'json_payload': data}) 

服务器:

 class Root(object): def __init__(self, content): self.content = content print self.content # this works exposed = True def GET(self): cherrypy.response.headers['Content-Type'] = 'application/json' return simplejson.dumps(self.content) @cherrypy.tools.json_in() @cherrypy.tools.json_out() def POST(self): self.content = cherrypy.request.json return {'status': 'success', 'message': 'updated'} 

更好的方法是:

 url = "http://xxx.xxxx.xx" datas = {"cardno":"6248889874650987","systemIdentify":"s08","sourceChannel": 12} headers = {'Content-type': 'application/json'} rsp = requests.post(url, json=datas, headers=headers) 

这适用于Python版本3.5,如果URL包含查询string/参数值,

请求URL = https://bah2.com/ws/rest/v1/concept/

参数值= 21f6bb43-98a1-419d-8f0c-8133669e40ca

 import requests r = requests.post('https://bah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca',auth=('username', 'password'),verify=False, json={"name": "Value"}) headers = {'Content-type': 'application/json'} print(r.status_code)