How do I set the request headers using Reqwest?

14,008

Solution 1

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

Solution 2

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.

Share:
14,008

Related videos on Youtube

serge1peshcoff
Author by

serge1peshcoff

I am a student and programmer. Learning Rails backend now.

Updated on September 14, 2022

Comments

  • serge1peshcoff
    serge1peshcoff over 1 year

    I need to make a GET request to a website with a cookie using the Reqwest library. I figured out how to send a GET request:

    let response = reqwest::get("http://example.com")?;
    

    How do I send the same request but adding some custom headers?

  • the_lrner
    the_lrner almost 4 years
    Thanks for digging deep. This should really be more explicit in the documentation.
  • cloudsurfin
    cloudsurfin over 3 years
    Can also now add multiple headers with .headers() instead of .header() and let mut headers = reqwest::header::HeaderMap::new(); headers.insert(reqwest::header::USER_AGENT,reqwest::header::‌​HeaderValue::from_st‌​atic("curl"));