The reqwest crate provides functions for both asynchronous and blocking http requests. Although in most cases you'd probably want to use the asynch calls, using the blocking calls is simpler, so we start with that.
This is what we add to the Cargo.toml
examples/simple-blocking-http-get-request/Cargo.toml
[package]
name = "simple-blocking-http-get-request"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
reqwest = { version = "0.11.20", features = ["blocking"] }
And this is the code:
examples/simple-blocking-http-get-request/src/main.rs
fn main() {
let res = match reqwest::blocking::get("https://httpbin.org/ip") {
Ok(res) => res,
Err(err) => {
println!("Error {}", err);
std::process::exit(1);
}
};
println!("{:?}", res);
println!("status: {:?}", res.status());
println!("server: {:?}", &res.headers()["server"]);
match res.text() {
Ok(val) => println!("{}", val),
Err(err) => eprintln!("Error: {}", err),
};
}
This is the output (slightly reformatted to make it easier to read).
Response {
url: Url {
scheme: "https",
cannot_be_a_base: false,
username: "",
password: None,
host: Some(Domain("httpbin.org")),
port: None,
path: "/ip",
query: None,
fragment: None
},
status: 200,
headers: {
"date": "Tue, 03 Oct 2023 13:12:58 GMT",
"content-type": "application/json",
"content-length": "31",
"connection": "keep-alive",
"server": "gunicorn/19.9.0",
"access-control-allow-origin": "*",
"access-control-allow-credentials": "true"
}
}
status: 200
server: "gunicorn/19.9.0"
{
"origin": "46.120.9.250"
}