python3 http.client/server post傳輸json問題
任務:
自己寫一個http.server/client傳輸json格式數(shù)據(jù)
從網(wǎng)上東拼西湊攢出來的,已經(jīng)調(diào)通了。(PS:想感謝兩位貼源碼的大神,但是找不到原網(wǎng)頁在哪了,抱歉!)
上代碼:
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發(fā)送的數(shù)據(jù)----------------") res1 = req_datas.decode('utf-8') res = json.loads(res1) print(res) print("--------------------接受client發(fā)送的數(shù)據(jù)------------------") 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'} #要發(fā)送的數(shù)據(jù) ,因為要轉成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端發(fā)送數(shù)據(jù) response = conn.getresponse() stc1 = response.read().decode('utf-8')#接受server端返回的數(shù)據(jù) stc = json.loads(stc1) print("-----------------接受server端返回的數(shù)據(jù)----------------") print(stc) print("-----------------接受server端返回的數(shù)據(jù)----------------") conn.close()
運行結果:
server端(client to server)
client端(server back client)
對于json應用的例子
首先要知道的是type(json) = str,傳輸?shù)臅r候也是以字符串格式傳輸,但其形式是字典:{‘aaa’:‘bbb’}。
在我的項目中,先利用json.dump()將字典轉成json格式
dict1 = {'aaa':'111'} jstr = json.dumps(dict1)
此時,我們看到的type(jstr) = str
在client給server傳輸?shù)臅r候,要將json轉成字節(jié)流
jstr1 = jstr.encode('utf-8')
在server端接受到的client端消息的時候就要解碼
jstr2 = jstr1.decode('utf-8')
然后再將json轉為字典類型
jstr3 = json.loads(jstr2)
總結
打完收工~
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
基于YUV 數(shù)據(jù)格式詳解及python實現(xiàn)方式
今天小編就為大家分享一篇基于YUV 數(shù)據(jù)格式詳解及python實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12如何基于python3和Vue實現(xiàn)AES數(shù)據(jù)加密
這篇文章主要介紹了如何基于python3和Vue實現(xiàn)AES數(shù)據(jù)加密,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03python實現(xiàn)Mysql數(shù)據(jù)庫批量新增數(shù)據(jù)的場景分析
這篇文章主要介紹了python實現(xiàn)Mysql數(shù)據(jù)庫批量新增數(shù)據(jù),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03python錯誤SyntaxError:?invalid?syntax的解決方法總結
SyntaxError: invalid syntax 是Python中常見的錯誤類型之一,它表示代碼中存在語法錯誤,下面這篇文章主要給大家介紹了關于python錯誤SyntaxError:?invalid?syntax的解決方法,需要的朋友可以參考下2024-08-08Python新手入門之單引號、雙引號與三引號的差異與應用示例
在Python當中表達字符串既可以使用單引號,也可以使用雙引號,那兩者有什么區(qū)別嗎?下面這篇文章主要給大家介紹了關于Python新手入門之單引號、雙引號與三引號的差異與應用示例,需要的朋友可以參考下2024-03-03