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
相关推荐
4***V2026 分钟前
Vue3响应式原理详解
开发语言·javascript·ecmascript
q***98527 分钟前
VS Code 中如何运行Java SpringBoot的项目
java·开发语言·spring boot
共享家952720 分钟前
QT-界面优化(中)
开发语言·qt
李日灐26 分钟前
手搓简单 string 库:了解C++ 字符串底层
开发语言·c++
say_fall35 分钟前
C语言编程实战:每日一题 - day7
c语言·开发语言
LiLiYuan.1 小时前
【Lombok库常用注解】
java·开发语言·python
Charles_go1 小时前
C#中级45、什么是组合优于继承
开发语言·c#
二川bro1 小时前
数据可视化进阶:Python动态图表制作实战
开发语言·python·信息可视化
q***2512 小时前
java进阶1——JVM
java·开发语言·jvm
while(1){yan}2 小时前
线程的状态
java·开发语言·jvm