我需要将一个JSON从客户端发布到服务器。我使用的是Python2.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(https://pypi.python.org/pypi/requests)中,支持“json”参数。无需指定“内容类型”。所以较短的版本:
对于2.4.2及更高版本的请求,您可以在调用中使用'json'参数,这使调用更简单。
编辑:此功能已添加到官方文档中。您可以在这里查看:Requests documentation
相关问题 更多 >
编程相关推荐