Making Requests

Make a HTTP GET request

reqwest-badge cat-net-badge

Parses the supplied URL and makes a synchronous HTTP GET request with reqwest::blocking::get. Prints obtained reqwest::blocking::Response status and headers. Reads HTTP response body into an allocated String using read_to_string.

use error_chain::error_chain; use std::io::Read; error_chain! { foreign_links { Io(std::io::Error); HttpRequest(reqwest::Error); } } fn main() -> Result<()> { let mut res = reqwest::blocking::get("http://httpbin.org/get")?; let mut body = String::new(); res.read_to_string(&mut body)?; println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers()); println!("Body:\n{}", body); Ok(()) }

Async

A similar approach can be used by including the tokio executor to make the main function asynchronous, retrieving the same information. Make sure to add tokio = {version = "1.21.2", features = ["full"]} to your cargo.toml file.

In this example, tokio::main handles all the heavy executor setup and allows sequential code implemented without blocking until .await.

Uses the asynchronous versions of reqwest, both reqwest::get and reqwest::Response.

use error_chain::error_chain; error_chain! { foreign_links { Io(std::io::Error); HttpRequest(reqwest::Error); } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let res = reqwest::get("http://httpbin.org/get").await?; println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers()); let body = res.text().await?; println!("Body:\n{}", body); Ok(()) }

Set custom headers and URL parameters for a REST request

reqwest-badge hyper-badge url-badge cat-net-badge

Builds complex URL with Url::parse_with_params. Sets standard headers header::USER_AGENT, and custom X-Powered-By header with RequestBuilder::HeaderName::TryFrom<&'a str> then makes the request with RequestBuilder::send.

The request target http://httpbin.org/headers responds with a JSON dict containing all request headers for easy verification.

use error_chain::error_chain; use reqwest::Url; use reqwest::blocking::Client; use reqwest::header::USER_AGENT; use serde::Deserialize; use std::collections::HashMap; error_chain! { foreign_links { Reqwest(reqwest::Error); UrlParse(url::ParseError); } } #[derive(Deserialize, Debug)] pub struct HeadersEcho { pub headers: HashMap<String, String>, } fn main() -> Result<()> { let url = Url::parse_with_params( "http://httpbin.org/headers", &[("lang", "rust"), ("browser", "servo")], )?; let response = Client::new() .get(url) .header(USER_AGENT, "Rust-test-agent") .header("X-Powered-By", "Rust") .send()?; assert_eq!( response.url().as_str(), "http://httpbin.org/headers?lang=rust&browser=servo" ); let out: HeadersEcho = response.json()?; assert_eq!(out.headers["User-Agent"], "Rust-test-agent"); assert_eq!(out.headers["X-Powered-By"], "Rust"); Ok(()) }