How do I add headers to a Reqwest client?

In Rust, the reqwest crate is widely used for making HTTP requests. When working with a reqwest::Client, you might want to customize the HTTP headers that are sent with a request. This can be useful for a variety of reasons, such as setting the User-Agent, Authorization for API keys, or Accept headers to specify the desired content type.

Here's how you can add headers to a reqwest::Client:

Firstly, you'll need to add reqwest to your Cargo.toml:

[dependencies]
reqwest = "0.11" # Make sure to use the latest version available

Then, in your Rust code, you can customize your client and headers as follows:

use reqwest::{header, Client, Error};

#[tokio::main]
async fn main() -> Result<(), Error> {
    // Create a `HeaderMap` and insert headers
    let mut headers = header::HeaderMap::new();
    headers.insert(header::USER_AGENT, "My Rust Program".parse().unwrap());
    headers.insert(header::ACCEPT, "application/json".parse().unwrap());
    headers.insert("Custom-Header", "Custom-Value".parse().unwrap());

    // Build a `Client` with the custom headers
    let client = Client::builder()
        .default_headers(headers)
        .build()?;

    // Now you can make a request with the client, and the headers will be included
    let res = client.get("http://httpbin.org/get")
        .send()
        .await?;

    println!("Status: {}", res.status());
    println!("Headers:\n{:#?}", res.headers());

    // Process the response as needed...

    Ok(())
}

In this example, we first create a mutable HeaderMap object and insert the desired headers. We then use Client::builder to construct a Client instance with the default_headers method, which sets the default headers for all requests made by this client. Note that you need to parse the header values into HeaderValue which may return an error, so we use unwrap for simplicity here. In a production environment, you should handle errors properly.

Once you have the client set up with the desired headers, you can use it to make HTTP requests. The headers you've set will be included in every request made by this client instance.

Remember that this example uses async code and requires the tokio runtime, as reqwest is an asynchronous HTTP client. Ensure that you have tokio added to your Cargo.toml:

tokio = { version = "1", features = ["full"] }

And make sure to await the asynchronous operations (send in this case).

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon