python3 http.client/server post传输json问题
作者:LyFxyy
这篇文章主要介绍了python3 http.client/server post传输json问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
任务:
自己写一个http.server/client传输json格式数据
从网上东拼西凑攒出来的,已经调通了。(PS:想感谢两位贴源码的大神,但是找不到原网页在哪了,抱歉!)
上代码:
http server端
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class Resquest(BaseHTTPRequestHandler):
def do_POST(self):
print(self.headers)
print(self.command)
req_datas = self.rfile.read(int(self.headers['content-length']))
print("--------------------接受client发送的数据----------------")
res1 = req_datas.decode('utf-8')
res = json.loads(res1)
print(res)
print("--------------------接受client发送的数据------------------")
data1 = {'bbb':'222'}
data = json.dumps(data1)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(data.encode('utf-8'))
if __name__ == '__main__':
host = ('localhost', 8888)
server = HTTPServer(host, Resquest)
print("Starting server, listen at: %s:%s" % host)
server.serve_forever()http client 端:
import http.client, urllib.parse
import json
diag1 = {'aaa':'111'} #要发送的数据 ,因为要转成json格式,所以是字典类型
data = json.dumps(diag1)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = http.client.HTTPConnection('localhost', 8888)
conn.request('POST', '/ippinte/api/scene/getall', data.encode('utf-8'), headers)#往server端发送数据
response = conn.getresponse()
stc1 = response.read().decode('utf-8')#接受server端返回的数据
stc = json.loads(stc1)
print("-----------------接受server端返回的数据----------------")
print(stc)
print("-----------------接受server端返回的数据----------------")
conn.close()运行结果:
server端(client to server)

client端(server back client)

对于json应用的例子
首先要知道的是type(json) = str,传输的时候也是以字符串格式传输,但其形式是字典:{‘aaa’:‘bbb’}。
在我的项目中,先利用json.dump()将字典转成json格式
dict1 = {'aaa':'111'}
jstr = json.dumps(dict1)此时,我们看到的type(jstr) = str

在client给server传输的时候,要将json转成字节流
jstr1 = jstr.encode('utf-8')在server端接受到的client端消息的时候就要解码
jstr2 = jstr1.decode('utf-8')然后再将json转为字典类型
jstr3 = json.loads(jstr2)
总结
打完收工~
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
