rust实现一个post小程序

主要是白天折磨了半天,无论如何post出去都不能成功,搞得我专门修改了一堆server的代码,以拦截任何访问服务器的数据,结果还是返回502,结果晚上回来一遍过,也真是奇怪的不行。先把一遍过的代码放出来,防止哪天又卡在这儿过不去。

//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"] }

意思很简单,就是访问路径为/dfc/get_block_stock,json数据为:

{"block_source": "gnn"}

后面就是打印结果了。居然直接一遍过了,在公司可是花了好几小时查遍了所有资料,也改遍了服务器的代码。

最后再贴出服务器的python测试代码: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.")

最后由于服务器运行用到了sanic组件和一个跨域组件,所以最后记得

pip install sanic
pip install sanic_cors

上一篇:STM32电机控制SDK介绍