904

我需要将 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())

有任何想法吗?

4

9 回答 9

1505

从 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'}
于 2014-10-13T16:08:06.177 回答
460

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

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)
于 2012-03-31T03:26:53.223 回答
85

从请求 2.4.2 ( https://pypi.python.org/pypi/requests ) 开始,支持“json”参数。无需指定“内容类型”。所以较短的版本:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})
于 2014-12-10T10:08:59.843 回答
50

data//之间需要使用哪个参数取决于一个名为的请求头json(可以通过浏览器的开发者工具查看)。filesContent-Type

Content-Type是时application/x-www-form-urlencoded,使用data=

requests.post(url, data=json_obj)

Content-Typeisapplication/json时,您可以只使用json=或使用data=并设置Content-Type自己:

requests.post(url, json=json_obj)
requests.post(url, data=jsonstr, headers={"Content-Type":"application/json"})

Content-Typeismultipart/form-data时,它用于上传文件,所以使用files=

requests.post(url, files=xxxx)
于 2020-04-12T07:53:21.387 回答
43

更好的办法是:</p>

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)
于 2017-05-04T07:26:32.503 回答
8

与 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'}
于 2017-01-20T21:10:59.513 回答
3
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)
于 2022-01-05T14:09:43.927 回答
0

我是这样解决的:

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


req = request.json
if not req :
    req = request.form
req['value']
于 2021-12-15T22:05:19.227 回答
-1

它始终建议我们需要具有读取 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
于 2021-03-19T14:44:25.457 回答