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

相关推荐

  1. rust实现一个post程序

    2024-04-09 06:10:02       42 阅读
  2. 微信程序post请求

    2024-04-09 06:10:02       29 阅读
  3. 微信程序实现一个天气预报应用程序

    2024-04-09 06:10:02       64 阅读
  4. 微信程序实现一个简单的登录功能

    2024-04-09 06:10:02       57 阅读
  5. 微信程序实现一个音乐播放器的功能

    2024-04-09 06:10:02       61 阅读
  6. 微信程序实现一个电影信息查询的应用程序

    2024-04-09 06:10:02       56 阅读
  7. 微信程序实现一个todolist这样的demo

    2024-04-09 06:10:02       66 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-09 06:10:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-09 06:10:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-09 06:10:02       87 阅读
  4. Python语言-面向对象

    2024-04-09 06:10:02       96 阅读

热门阅读

  1. 设计模式:生活中的责任链模式

    2024-04-09 06:10:02       39 阅读
  2. 【Python】OPC UA 服务器与客户端的实现

    2024-04-09 06:10:02       39 阅读
  3. 【使用 Qt 实现计算器】

    2024-04-09 06:10:02       30 阅读
  4. WKWebView生成PDF

    2024-04-09 06:10:02       34 阅读
  5. 算力服务器租用的费用包含哪些方面?

    2024-04-09 06:10:02       31 阅读
  6. python实现假设检验-z检验

    2024-04-09 06:10:02       36 阅读
  7. 国内镜像源拉取Ubuntu,并实现网络配置

    2024-04-09 06:10:02       40 阅读
  8. Python的学习之路

    2024-04-09 06:10:02       39 阅读
  9. RFID详解

    2024-04-09 06:10:02       38 阅读
  10. C语言的数组

    2024-04-09 06:10:02       33 阅读
  11. 速盾:游戏cdn什么意思

    2024-04-09 06:10:02       41 阅读
  12. html实现登录界面

    2024-04-09 06:10:02       34 阅读
  13. 中国联通软件研究院春招3场面试Offer面经

    2024-04-09 06:10:02       90 阅读
  14. PyCharm详细安装教程与高效使用指南

    2024-04-09 06:10:02       41 阅读