使用Python请求发布JSON

发布于 2021-02-02 23:22:35

我需要将JSON从客户端发布到服务器。我正在使用Python 2.7.1和simplejson。客户端正在使用请求。服务器是CherryPy。我可以从服务器获取硬编码的JSON(代码未显示),但是当我尝试将JSON POST到服务器时,会收到“ 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())

有任何想法吗?

关注者
0
被浏览
131
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看