我需要POST一个JSON从客户端到服务器。我使用的是Python 2.7.1和simplejson。客户端正在使用请求。服务器为CherryPy。我可以得到一个硬编码的JSON从服务器(代码未显示),但当我试图POST一个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())

什么好主意吗?


当前回答

headers = {"charset": "utf-8", "Content-Type": "application/json"}
url = 'http://localhost:PORT_NUM/FILE.php'

r = requests.post(url, json=YOUR_JSON_DATA, headers=headers)
print(r.text)

其他回答

我是这样解决的:

from flask import Flask, request
from flask_restful import Resource, Api


req = request.json
if not req :
    req = request.form
req['value']

更好的方法是:

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)

适用于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'}

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

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

它总是建议我们需要具备读取JSON文件并将对象解析为请求体的能力。我们不打算解析请求中的原始数据,因此下面的方法将帮助您解析它。

def POST_request():
    with open("FILE PATH", "r") as data:
        JSON_Body = data.read()
    response = requests.post(url="URL", data=JSON_Body)
    assert response.status_code == 200