Last active
August 17, 2025 07:54
-
-
Save hzbd/084ccce261dd82b12d49052f05a634d9 to your computer and use it in GitHub Desktop.
rust reqwest demo with headers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use reqwest::header::{HeaderMap, HeaderName, USER_AGENT, HeaderValue, CONTENT_TYPE}; | |
| use serde::{Deserialize, Serialize}; | |
| // use serde_json::json; | |
| #[derive(Serialize, Deserialize, Debug)] | |
| struct APIResponse { | |
| http_via: String, | |
| http_x_forwarded_for: String, | |
| client_ip: String, | |
| server: String, | |
| at: String, | |
| } | |
| #[tokio::main] | |
| async fn main() { | |
| let url = format!("https://dadou.run/my"); | |
| fn construct_headers() -> HeaderMap { | |
| let mut headers = HeaderMap::new(); | |
| headers.insert(USER_AGENT, HeaderValue::from_static("reqwest")); | |
| headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); | |
| headers.insert(HeaderName::from_static("x-api-key"), HeaderValue::from_static("123-123-123")); | |
| headers | |
| } | |
| let client = reqwest::Client::new(); | |
| let response = client | |
| .get(url) | |
| .headers(construct_headers()) | |
| .send() | |
| .await | |
| .unwrap(); | |
| println!("Success! {:?}", response); | |
| match response.status() { | |
| reqwest::StatusCode::OK => { | |
| // on success, parse our JSON to an APIResponse | |
| match response.json::<APIResponse>().await { | |
| Ok(parsed) => println!("Success! {:?}", parsed), | |
| Err(_) => println!("Hm, the response didn't match the shape we expected."), | |
| }; | |
| } | |
| reqwest::StatusCode::UNAUTHORIZED => { | |
| println!("Need to grab a new token"); | |
| } | |
| other => { | |
| panic!("Uh oh! Something unexpected happened: {:?}", other); | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@InShade
The reason
client_Headers: {}prints an emptyHeaderMapis due to howreqwesthandles default headers and request building:client.default_headers(headers): This line sets the providedheadersas default headers for thereqwest::Clientinstance. These headers are associated with the client itself, not immediately with individualRequestobjects you build.let r: reqwest::Request = client.get("http://dadou.run/my").build()?;: When you callbuild()on a request builder, you are creating areqwest::Requestobject (r). At this point, thisrobject only contains headers that were explicitly added during its construction (e.g., if you used.header("Key", "Value")in the chain). TheClient'sdefault_headershave not yet been merged into thisrobject.reqwestlibrary internally applies theClient'sdefault_headersto theRequestobject only whenclient.execute(r).await?(orclient.send(r).await?) is called. This merging process happens just before the request is actually sent over the network.Therefore, when you print
r.headers(), you are inspecting the headers of theRequestobject before theClient's default headers have been merged into it. This is expected behavior, and it does not mean that yourX-MY-HEADERandCOOKIEheaders will not be sent; they will be sent whenclient.execute(r)is called.println!("client_Headers: {:#?}", r.headers()); cannot be placed anywhere in your code to print the complete set of headers, including the Client's default headers, before client.execute() is called.
Your requirement (to print the complete request headers, including Client's default headers, before sending) cannot be directly achieved using reqwest's public API. You must rely on external tools (like network packet sniffers/proxies) or server-side logging/echoing to verify that these headers are indeed sent.