Simple blocking HTTP GET request in Rust

reqwest blocking HTTP GET

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"
}

Related Pages

Reqwest the HTTP client library of Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo