Reqwest client, how to retrieve default headers that are already set

How can I ensure that both the default headers (X-Custom-Header, USER_AGENT) and the per-request headers are printed in the following code? Currently, only the per-request headers are being printed, and the headers set in default_headers are missing. How can I fix this?

use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};
use reqwest::{Client, Request};

fn main() {
    // Define the default headers for all requests.
    let mut headers = HeaderMap::new();
    headers.insert("X-Custom-Header", HeaderValue::from_static("custom_value"));
    headers.insert(USER_AGENT, HeaderValue::from_static("my-agent"));

    // Create the client with default headers
    let client = Client::builder()
        .default_headers(headers)
        .build()
        .unwrap();
    
    // Add per request headers
    let mut headers = HeaderMap::new();
    headers.insert("xyz", HeaderValue::from_static("1"));

    // Create a RequestBuilder and build the request
    let request: Request = client.get("https://example.com/")
        .headers(headers)
        .build()
        .unwrap();

    // Access the full headers that will be sent with the request
    let request_headers = request.headers();

    // Print the headers
    for (key, value) in request_headers.iter() {
        println!("{}: {:?}", key, value);
    }
}

You can't without referring to the Client instance that will actually execute the Request you created. The default headers of the client are not part of the request, they are only added by the client immediately before sending it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.