rust實(shí)現(xiàn)post小程序(完整代碼)
主要是白天折磨了半天,無(wú)論如何post出去都不能成功,搞得我專門修改了一堆server的代碼,以攔截任何訪問(wèn)服務(wù)器的數(shù)據(jù),結(jié)果還是返回502,結(jié)果晚上回來(lái)一遍過(guò),也真是奇怪的不行。先把一遍過(guò)的代碼放出來(lái),防止哪天又卡在這兒過(guò)不去。
//main.rs use reqwest::Error; //main.rs async fn post_request() -> Result<(), Error> { let url = "http://localhost:30241/dfc/get_block_stock"; let json_data = r#"{"block_source": "gnn"}"#; let client = reqwest::Client::new(); let response = client .post(url) .header("Content-Type", "application/json") .body(json_data.to_owned()) .send() .await?; println!("Status Code: {}", response.status()); let response_body = response.text().await?; println!("Response body: \n{}", response_body); Ok(()) } #[tokio::main] async fn main() -> Result<(), Error> { post_request().await?; Ok(()) }
Cargo.toml文件如下:
[package] name = "untitled" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] tokio = { version = "1.15", features = ["full"] } reqwest = { version = "0.11.22", features = ["json"] }
意思很簡(jiǎn)單,就是訪問(wèn)路徑為/dfc/get_block_stock,json數(shù)據(jù)為:
{"block_source": "gnn"}
后面就是打印結(jié)果了。居然直接一遍過(guò)了,在公司可是花了好幾小時(shí)查遍了所有資料,也改遍了服務(wù)器的代碼。
最后再貼出服務(wù)器的python測(cè)試代碼:my_http_server.py
from sanic import Sanic from sanic import response, request from sanic_cors import CORS app = Sanic(name='my-http-server') CORS(app) def success_msg(err_code=0): res = dict() res["err_code"] = err_code res["err_msg"] = "success" return res @app.middleware("response") def cors_middle_res(request: request.Request, response: response.HTTPResponse): """跨域處理""" allow_origin = '*' response.headers.update( { 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE', 'Access-Control-Allow-Headers': 'Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization', } ) @app.route("/dfc/get_block_stock", methods=['POST']) async def order_buy_sell(request): print("order_buy_sell: from: {}, path: {}, data: {}".format(request.socket[0], request.path, request.json)) res = success_msg(0) result = dict() res["result"] = result return response.json(res)
然后是main.py
from my_http_server import app # Press the green button in the gutter to run the script. if __name__ == '__main__': try: port = 30241 print("my-http-server will started, serving at http://localhost:{}".format(port)) app.run(host="0.0.0.0", port=port) except KeyboardInterrupt: print("python-sanic-http-server error.")
最后由于服務(wù)器運(yùn)行用到了sanic組件和一個(gè)跨域組件,所以最后記得
pip install sanic pip install sanic_cors
到此這篇關(guān)于rust實(shí)現(xiàn)一個(gè)post小程序的文章就介紹到這了,更多相關(guān)rust post小程序內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Windows系統(tǒng)下安裝Rust環(huán)境超詳細(xì)教程
這篇文章主要介紹了如何在Windows系統(tǒng)上安裝mingw64和Rust,mingw64是一個(gè)輕便的C語(yǔ)言編譯環(huán)境,可以替代Rust默認(rèn)使用的Visual?Studio,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2025-02-02Rust動(dòng)態(tài)數(shù)組Vec基本概念及用法
Rust中的Vec是一種動(dòng)態(tài)數(shù)組,它可以在運(yùn)行時(shí)自動(dòng)調(diào)整大小,本文主要介紹了Rust動(dòng)態(tài)數(shù)組Vec基本概念及用法,具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12rust?創(chuàng)建多線程web?server的詳細(xì)過(guò)程
web?server?中主要的兩個(gè)協(xié)議是?http?和?tcp,tcp?是底層協(xié)議,http?是構(gòu)建在?tcp?之上的,本篇文章重點(diǎn)給大家介紹rust?創(chuàng)建多線程web?server的詳細(xì)過(guò)程,感興趣的朋友跟隨小編一起看看吧2023-11-11Rust編寫自動(dòng)化測(cè)試實(shí)例權(quán)威指南
這篇文章主要為大家介紹了Rust編寫自動(dòng)化測(cè)試實(shí)例權(quán)威指南詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12