如何使用Python请求发布JSON数据?
我需要将JSON从客户端发布到服务器。我正在使用Python 2.7.1和simplejson。客户端正在使用请求。服务器是樱桃色的。我可以从服务器获取硬编码的JSON(代码未显示),但当我尝试将JSON发布到服务器时,会得到“400错误请求” 这是我的客户代码:如何使用Python请求发布JSON数据?,python,json,python-requests,cherrypy,Python,Json,Python Requests,Cherrypy,我需要将JSON从客户端发布到服务器。我正在使用Python 2.7.1和simplejson。客户端正在使用请求。服务器是樱桃色的。我可以从服务器获取硬编码的JSON(代码未显示),但当我尝试将JSON发布到服务器时,会得到“400错误请求” 这是我的客户代码: data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'} data_json = simplejson.dumps(data)
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())
有什么想法吗?原来我缺少标题信息。以下工作:
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)
从请求版本2.4.2开始,您可以在调用中使用(使用字典)而不是
数据=
(使用字符串):
>>> 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'}
在requests 2.4.2()中,支持“json”参数。无需指定“内容类型”。因此,较短的版本:
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
与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'}
更好的方法是:
url = "http://xxx.xxxx.xx"
data = {
"cardno": "6248889874650987",
"systemIdentify": "s08",
"sourceChannel": 12
}
resp = requests.post(url, json=data)
需要使用
数据
/json
/文件
之间的哪个参数取决于名为的请求头(您可以通过浏览器的开发人员工具进行检查)
当内容类型
为应用程序/x-www-form-urlencoded
时,使用数据=
:
requests.post(url,data=json_obj)
当内容类型
为应用程序/json
时,您可以直接使用json=
或使用数据=
自己设置内容类型
:
requests.post(url,json=json_obj)
requests.post(url,data=jsonstr,headers={“Content Type”:“application/json”})
当内容类型
为多部分/表单数据
时,它用于上载文件,因此使用文件=
:
requests.post(url,files=xxxx)
始终建议我们需要能够读取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
我使用的是一个直接来自的示例的精简版本。我的评论仍然有效-CherryPy不使用
内容
参数调用类\uuuuu init\uuuuu
方法(并且不声称在您提供的链接中)。在他们提供的详细示例中,用户提供调用\uuuu init\uuuu
的代码并提供参数,我们在这里没有看到这些参数,因此我不知道当您的\this works
注释相关时对象处于什么状态。您是否要求查看创建实例的行?是的,我试图启动您的示例以测试它,但我不确定您是如何实例化它的。代码已经更改。我现在创建它,没有额外的参数cherrypy.quickstart(Root(),“/”,conf)
。好消息-我在GET
中看到了您的应用程序/json
,但不知怎的错过了您没有在请求中提供它的信息。您可能还需要确保从POST
返回一些内容,或者您可能会得到500
。这似乎不是必需的。当我打印r
时,我得到了
。我如何在服务器端检索这个json?r=requests.get(')c=r.content result=simplejson.load(c)在这里使用json.dumps
之前稍微提前一点。请求
的数据
参数可以很好地用于字典。无需转换为字符串。将其设置为可接受的答案,因为这在2.4.2中更为惯用。请记住,对于疯狂的unicode,这可能不起作用。我看到了一个例子,它在发送之前使用dict对象并执行json.dumps(object)。不要这样做…它会弄乱你的JSON。以上是完美的。您可以向它传递一个python对象,它将变成完美的json。@MydKnight查看源代码,请求设置内容类型,然后将结果从str
转换为bytes
“更好的方法是”在正确答案出现3年后不要发布错误答案-1+1. 如果您正在使用curlify
查看从响应发出的请求,则不会设置内容类型标题,除非您按照以下说明操作<代码>打印(curlify.to_curl(project.request))