http传输json文件_python

https://cloud.tencent.com/developer/article/1571365
http传输图片
https://www.cnblogs.com/jruing/p/12215688.html
python自带http服务
https://www.cnblogs.com/ngbjng/p/11994336.html
python中的HTTP传输
https://blog.csdn.net/testcs_dn/article/details/50449106
Python实现基于HTTP文件传输实例

任务:自己写一个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()

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值