【问题标题】:Grabbing a response header value with reqwest in rust在 rust 中使用 reqwest 获取响应标头值
【发布时间】:2020-12-31 11:33:53
【问题描述】:

在过去的几天里,我主要是在试验 reqwest 模块,看看我能完成什么,但我遇到了一个我无法解决的问题。我尝试在执行发布请求后检索响应标头值。我尝试的代码是

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());
}

此代码似乎返回此错误

error[E0599]: no method named `headers` found for opaque type `impl std::future::Future` in the current scope

【问题讨论】:

    标签: rust reqwest


    【解决方案1】:

    最新的reqwest 默认是async,所以在你的例子中res 是一个未来,而不是实际的响应。您要么需要await 响应,要么使用reqwest 的阻塞API。

    异步/等待

    在您的 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()
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 2019-02-18
      • 2015-11-15
      • 2016-11-16
      相关资源
      最近更新 更多