如何使用 Python 请求发布 JSON 数据?

新手上路,请多包涵

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

这是我的客户端代码:

 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())

有任何想法吗?

原文由 Charles R 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 291
2 个回答

从 Requests 版本 2.4.2 开始,您可以在调用中使用 json= 参数(采用字典)代替 data= (采用字符串):

 >>> 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': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

原文由 Zeyang Lin 发布,翻译遵循 CC BY-SA 4.0 许可协议

事实证明我缺少标题信息。以下作品:

 import requests

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)

原文由 Charles R 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题