我正在尝试使用 reqwest crate of rust 发出发布请求。这是 cargo.toml 的片段
[dependencies]
tokio = { version = "0.2", features = ["full"] }
reqwest = { version = "0.10", features = ["json"] }
这是我向简单服务器发出请求的代码片段。
use reqwest::{Response, StatusCode};
use serde_json::{json, Value};
#[tokio::main]
async fn main() -> Result< (), reqwest::Error> {
let map1 = json!({
"abc":"abc",
"efg":"efg"
});
let body: Value = reqwest::Client::new()
.post("http://localhost:4000/hello")
.json(&map1)
.send()
.await?
.json()
.await?;
println!("Data is : {:?}", body);
Ok(())
}
使用简单服务器箱编写的代码片段如下:
use simple_server::{Server, StatusCode};
fn main() {
let server = Server::new(|req, mut response| {
println!(
"Request received {} {} {:?}",
req.method(),
req.uri(),
&req.body()
);
match (req.method().as_str(), req.uri().path()) {
("GET", "/") => Ok(response.body(format!("Get request").into_bytes())?),
("POST", "/hello") => Ok(response.body(format!("Post request").into_bytes())?),
(_, _) => {
response.status(StatusCode::NOT_FOUND);
Ok(response.body(String::from("Not Found").into_bytes())?)
}
}
});
server.listen("127.0.0.1", "4000");
}
我得到的输出是:
Request received POST /hello []
所需的输出是字节向量数组,但我收到的是一个空向量数组。
我已经尝试过的解决方案是:
所以我认为问题一定出在这个简单的服务器机箱上。 每一个有值(value)的建议都会得到鼓励。
最佳答案
use reqwest::{Response, StatusCode};
use serde_json::{json, Value};
#[tokio::main]
async fn main() -> Result<String> {
let map1 = json!({
"abc":"abc",
"efg":"efg"
});
let body: Value = reqwest::Client::new()
.post("http://localhost:4000/hello")
.json(&map1)
.send()
.await?
.json()
.await?;
println!("Data is : {:?}", body);
let resp = serde_json::to_string(&body).unwrap();
Ok(resp)
}
关于rust - 从 "reqwest"crate rust 发出 post 请求时请求正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61321173/