原文链接: tornado处理post请求的json数据
方式一, urllib.parse.urlencode
代码
server
1 2 3 4 5 6 7 8 9
| class MainHandler(RequestHandler): def post(self): param = self.get_argument('param') print(type(param)) print(param) param = eval(param) print(type(param)) print(param) self.write('OK')
|
client
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import urllib.parse import urllib.request url = "http://172.16.1.239:8888/" req_dict = {'param': 'param'} req_encode = urllib.parse.urlencode(req_dict) req_post = req_encode.encode('utf-8') print(req_post) headers = {} req = urllib.request.Request(url=url, headers=headers, data=req_post) res = urllib.request.urlopen(req) res = res.read().decode('utf-8')
|
输出
server
1 2 3 4
| <class 'str'> {'k': 'v'} <class 'dict'> {'k': 'v'}
|
client
1 2
| b'param=%7B%27k%27%3A+%27v%27%7D' OK
|
方式二, json
代码
server
1 2 3 4 5 6
| class MainHandler(RequestHandler): def post(self): param = self.request.body.decode('utf-8') prarm = json.loads(param) print(param) self.write('Ok')
|
client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import json import urllib.parse import urllib.request url = "http://172.16.1.239:8888/" param = {'k': 'v'} req_dict = {'param': param} req_json = json.dumps(req_dict) req_post = req_json.encode('utf-8') print(req_post) headers = {'Content-Type': 'application/json'} req = urllib.request.Request(url=url, headers=headers, data=req_post) res = urllib.request.urlopen(req) res = res.read().decode('utf-8') print(res)
|
输出
server
client
1 2
| b'{"param": {"k": "v"}}' OK
|
方式二client请求方式一的server, server会报如下错误
WARNING:tornado.general:400 POST /start_plus (172.16.1.239): Missing argument param
同样
方式一client请求方式二的server, server会报如下错误
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)