Grabbing a response header value with reqwest in rust

2.8k Views Asked by At

Ive mainly been experimenting with the reqwest module over the past few days to see what i can accomplish, but i came over a certain problem which im not able to resolve. Im trying to retrieve the a response headers value after doing a post request. The code in which i tried is

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

This code seems to return this error

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

There are 1 best solutions below

0
On BEST ANSWER

The latest reqwest is async by default, so in your example res is a future, not the actual response. Either you need to await the response or use reqwest's blocking API.

async/await

In your Cargo.toml add tokio as a dependency.

[dependencies]
tokio = { version = "0.2.22", features = ["full"] }
reqwest = "0.10.8"

Use tokio as the async runtime and await the response.

#[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(())
}

Blocking API

In your Cargo.toml enable the blocking feature.

[dependencies]
reqwest = { version = "0.10.8", features = ["blocking"] }

Now you can use the Client from the reqwest::blocking module.

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