make a get request with headers in rust

To make a GET request with headers in Rust, you can use the reqwest crate. Here is an example:

main.rs
use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://httpbin.org/get";
    let mut headers = HeaderMap::new();
    headers.insert(USER_AGENT, HeaderValue::from_str("reqwest").unwrap());

    let client = reqwest::Client::builder()
        .default_headers(headers)
        .build()?;

    let response = client.get(url).send()?;
    println!("Response status: {}", response.status());

    Ok(())
}
483 chars
17 lines

In this example, we first create a HeaderMap object and add the header we want to send, in this case a User-Agent header. Then, we create a reqwest::Client object and set the default headers to the HeaderMap we just created. Finally, we make a GET request with the client and the URL, and the headers will be automatically added to the request.

Note that we wrap the code in main() in a Result to handle errors. And we print the HTTP status code of the response for verification.

related categories

gistlibby LogSnag