rust - 从 "reqwest" crate rust 发出 post 请求时,请求正文为空
问题描述
我正在尝试使用 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 []
所需的输出是字节向量数组,但我收到一个空向量数组。
我已经尝试过的解决方案是:
- 使用 Postman 向同一服务器发出 post 请求,它工作正常。
- 使用相同的 reqwest 代码向任何其他服务器(如 hyper、actix 等)发出 post 请求,它工作正常。
- 发送一个简单的正文作为 post 请求的正文(没有 JSON )。但同样的问题也会发生。
所以我认为问题一定出在这个简单的服务器箱上。每一个有价值的建议都会受到鼓励。
解决方案
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)
}
推荐阅读
- css - 计算正确的排水沟
- ios - UIScrollView 上的 Next Prev 按钮
- .net - VSTO ClickOnce 部署配置值
- javascript - 如何迭代数组的元素并在 javascript 的中间显示一条消息?
- java - 为什么此方法每次都将第一个答案作为正确答案返回?
- jmx - 使用 AMQ 7.0.1 进行 AppDynamics 监控
- mongodb - 为什么我无法在 MongoDB 中指定使用投影参数返回的字段?
- linux - 如何每隔 5 小时运行一次 cron 作业
- azure-servicebus-queues - com.microsoft.azure .servicebus.primitives.ServiceBusException
- c++ - 安全使用 strcpy