How do I set the request headers using Reqwest?

Reqwest 0.10

Starting at the crate’s documentation, we see:

For a single request, you can use the get shortcut method.

get‘s documentation states:

This function creates a new internal Client on each call, and so should not be used if making many requests. Create a Client instead.

Client has a request method which states:

Returns a RequestBuilder, which will allow setting headers and request body before sending.

RequestBuilder has a header method. This can be used as:

use reqwest::header::USER_AGENT;

let client = reqwest::Client::new();
let res = client
    .get("https://www.rust-lang.org")
    .header(USER_AGENT, "My Rust Program 1.0")
    .send()
    .await?;

How do I add custom headers?

If you look at the signature for header, you will see that it accepts generic types:

pub fn header<K, V>(self, key: K, value: V) -> RequestBuilder where
    HeaderName: TryFrom<K>,
    <HeaderName as TryFrom<K>>::Error: Into<Error>,
    HeaderValue: TryFrom<V>,
    <HeaderValue as TryFrom<V>>::Error: Into<Error>, 

There is an implementation of TryFrom<&'a str> for HeaderName, so you can use a string literal:

use reqwest; // 0.10.0
use tokio; // 0.2.6

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = reqwest::Client::new();
    let res = client
        .get("https://www.rust-lang.org")
        .header("X-My-Custom-Header", "foo")
        .send()
        .await?;

    Ok(())
}

Leave a Comment

deneme bonusudeneme bonusu veren sitelerOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino