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
相关推荐
m0_748708051 分钟前
C++中的观察者模式实战
开发语言·c++·算法
qq_5375626713 分钟前
跨语言调用C++接口
开发语言·c++·算法
wjs202424 分钟前
DOM CDATA
开发语言
Tingjct25 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
猷咪1 小时前
C++基础
开发语言·c++
IT·小灰灰1 小时前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧1 小时前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q1 小时前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳01 小时前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言
是誰萆微了承諾1 小时前
php 对接deepseek
android·开发语言·php