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

Send Cookie in reqwest client with version ~0.9.19

use reqwest; // 0.9.19
use http::{HeaderMap, HeaderValue, header::{COOKIE}};

// create client first
let init_client = reqwest::Client::builder()
        .cookie_store(true).build().unwrap();
// create Header Map
// Here cookie store is optional based on if making more than one request with the // same client 
let mut headers = HeaderMap::new();
headers.insert(COOKIE, HeaderValue::from_str("key=value").unwrap());
let resp = init_client.get("api")
           .headers(headers)
           .query(&[("name", "foo")])
           .send()
           .map(|resp|{
               println!("{:?}", resp.status());
               resp
           })
           .map_err(|err|{
              println!("{:?}", err);
              err
           });

Hope This may help.