http-client async with reqwest
In order to send asynchronous requests we need to depend on both the reqwest crate and on tokio that provides the asynchronous runtime.
For the latter we add the full feature so we won't need to worry about anything missing.
cargo add reqwest
cargo add tokio -F full
Cargo.toml
[package]
name = "http-client"
version = "0.1.0"
edition = "2024"
[dependencies]
reqwest = "0.11"
tokio = { version = "1", features = ["full"] }
The Code
In this example we are not particularily interested in any specific errors, so we handle them using the ? operator that, in this case, will make our program exit with a non-zero exit code.
The text method will return the content of the web page. As we are accessing the main page of httpbin.org that should be some HTML document.
#[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let url = get_url(""); let html = reqwest::get(url).await?.text().await?; println!("{html}"); Ok(()) } fn get_url(path: &str) -> String { let host = std::env::args().nth(1).unwrap_or("httpbin.org".into()); let url = if host == "localhost" { format!("http://localhost/{path}") } else { format!("https://{host}/{path}") }; url }
- reqwest
- async
- tokio