rust实现一个post小程序

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

rust 复制代码
//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文件如下:

bash 复制代码
[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

python 复制代码
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

python 复制代码
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组件和一个跨域组件,所以最后记得

bash 复制代码
pip install sanic
pip install sanic_cors
相关推荐
CCPC不拿奖不改名1 分钟前
Python基础:python语言中的文件操作+面试题目
开发语言·数据结构·人工智能·python·学习·面试·职场和发展
superman超哥2 分钟前
Rust 借用分割技巧:突破借用限制的精确访问
开发语言·后端·rust·编程语言·借用分割技巧·借用限制·精准访问
程序炼丹师3 分钟前
C++ 中的 std::tuple (元组)的使用
开发语言·c++
程序员佳佳8 分钟前
【万字硬核】从GPT-5.2到Sora2:深度解构多模态大模型的“物理直觉”与Python全栈落地指南(内含Banana2实测)
开发语言·python·gpt·chatgpt·ai作画·aigc·api
不绝19114 分钟前
C#进阶——内存
开发语言·c#
风送雨15 分钟前
Go 语言进阶学习:第 1 周 —— 并发编程深度掌握
开发语言·学习·golang
小北方城市网17 分钟前
第 5 课:服务网格(Istio)实战|大规模微服务的流量与安全治理体系
大数据·开发语言·人工智能·python·安全·微服务·istio
jghhh0118 分钟前
自适应信号时频处理方法MATLAB实现(适用于非线性非平稳信号)
开发语言·算法·matlab
AC赳赳老秦18 分钟前
Go语言微服务文档自动化生成:基于DeepSeek的智能解析实践
大数据·开发语言·人工智能·微服务·golang·自动化·deepseek
古城小栈18 分钟前
Rust 之 迭代器
开发语言·rust