rust request get headers
To send a GET request with headers in Rust, you can use the reqwest crate. Here's an example:
use reqwest::header;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let response = client
.get("https://example.com")
.header(header::USER_AGENT, "My Rust App")
.header(header::CONTENT_TYPE, "application/json")
.send()
.await?;
println!("Response status: {}", response.status());
Ok(())
}
In this example, we first create a reqwest::Client
instance. Then, we use the get
method on the client to make a GET request to the specified URL (https://example.com
). We set the desired headers using the header
module from the reqwest
crate, and pass them to the header
method on the request builder.
After sending the request with the send
method, we can access the response and its properties. In this example, we simply print the response status using response.status()
.
Remember to add the reqwest
crate to your Cargo.toml
file:
[dependencies]
reqwest = "0.11"
tokio = { version = "1", features = ["full"] }
This example uses the tokio
crate for asynchronous execution, so make sure to include it as well.
I hope this helps! Let me know if you have any further questions.