使用 Rust 中的 reqwest 获取响应 header 值
Grabbing a response header value with reqwest in rust
过去几天我主要是在试验 reqwest 模块,看看我能完成什么,但我遇到了一个我无法解决的问题。我试图在执行 post 请求后检索响应 headers 值。我试过的代码是
extern crate reqwest;
fn main() {
let client = reqwest::Client::new();
let res = client
.post("https://google.com")
.header("testerheader", "test")
.send();
println!("Headers:\n{:#?}", res.headers().get("content-length").unwrap());
}
这段代码好像return这个错误
error[E0599]: no method named `headers` found for opaque type `impl std::future::Future` in the current scope
默认情况下,最新的 reqwest
是 async
,因此在您的示例中,res
是未来,而不是实际响应。您需要 await
响应或使用 reqwest
的阻止 API.
async/await
在您的 Cargo.toml 中添加 tokio
作为依赖项。
[dependencies]
tokio = { version = "0.2.22", features = ["full"] }
reqwest = "0.10.8"
使用 tokio
作为异步运行时和 await
响应。
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let res = client
.post("https://google.com")
.header("testerheader", "test")
.send()
.await?;
println!(
"Headers:\n{:#?}",
res.headers().get("content-length").unwrap()
);
Ok(())
}
阻塞API
在您的 Cargo.toml 中启用 blocking
功能。
[dependencies]
reqwest = { version = "0.10.8", features = ["blocking"] }
现在您可以使用 reqwest::blocking
模块中的 Client
。
fn main() {
let client = reqwest::blocking::Client::new();
let res = client
.post("https://google.com")
.header("testerheader", "test")
.send()
.unwrap();
println!(
"Headers:\n{:#?}",
res.headers().get("content-length").unwrap()
);
}
过去几天我主要是在试验 reqwest 模块,看看我能完成什么,但我遇到了一个我无法解决的问题。我试图在执行 post 请求后检索响应 headers 值。我试过的代码是
extern crate reqwest;
fn main() {
let client = reqwest::Client::new();
let res = client
.post("https://google.com")
.header("testerheader", "test")
.send();
println!("Headers:\n{:#?}", res.headers().get("content-length").unwrap());
}
这段代码好像return这个错误
error[E0599]: no method named `headers` found for opaque type `impl std::future::Future` in the current scope
默认情况下,最新的 reqwest
是 async
,因此在您的示例中,res
是未来,而不是实际响应。您需要 await
响应或使用 reqwest
的阻止 API.
async/await
在您的 Cargo.toml 中添加 tokio
作为依赖项。
[dependencies]
tokio = { version = "0.2.22", features = ["full"] }
reqwest = "0.10.8"
使用 tokio
作为异步运行时和 await
响应。
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let res = client
.post("https://google.com")
.header("testerheader", "test")
.send()
.await?;
println!(
"Headers:\n{:#?}",
res.headers().get("content-length").unwrap()
);
Ok(())
}
阻塞API
在您的 Cargo.toml 中启用 blocking
功能。
[dependencies]
reqwest = { version = "0.10.8", features = ["blocking"] }
现在您可以使用 reqwest::blocking
模块中的 Client
。
fn main() {
let client = reqwest::blocking::Client::new();
let res = client
.post("https://google.com")
.header("testerheader", "test")
.send()
.unwrap();
println!(
"Headers:\n{:#?}",
res.headers().get("content-length").unwrap()
);
}