Make HTTP requests
Recipe | Crates | Categories |
---|---|---|
Make a HTTP GET request | ||
Make a HTTP GET request asynchronously | ||
Set custom headers and URL parameters for a REST request |
Make a HTTP GET request
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 std::string::String
⮳ using std::io::Read::read_to_string
⮳.
use std::io::Read; use anyhow::Result; 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(()) }
Make a HTTP GET request asynchronously
A similar approach can be used by including the tokio
⮳ executor to make the main function asynchronous, retrieving the same information.
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 anyhow::Result; #[tokio::main] async fn main() -> Result<()> { 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
Sets both standard and custom HTTP headers as well as URL parameters for a HTTP GET request. Creates a custom header of type XPoweredBy
with hyper::header!
⮳ macro.
Builds complex URL with url::Url::parse_with_params
⮳. Sets standard headers
hyper::header::USER_AGENT
⮳ hyper::header::AUTHORIZATION
⮳ and custom XPoweredBy
with reqwest::RequestBuilder::header
⮳, then makes the request with
reqwest::RequestBuilder::send
⮳.
The request targets http://httpbin.org/headers service which responds with a JSON dict containing all request headers for easy verification.
use std::collections::HashMap; use anyhow::Result; use reqwest::header; use serde::Deserialize; #[derive(Deserialize, Debug)] pub struct HeadersEcho { pub headers: HashMap<String, String>, } fn main() -> Result<()> { // Parse an absolute URL from a string and add params to its query string let url = url::Url::parse_with_params("http://httpbin.org/headers", &[ ("lang", "rust"), ("browser", "servo"), ])?; // Define default headers for all requests let mut default_headers = header::HeaderMap::new(); default_headers .insert("X-MY-HEADER", header::HeaderValue::from_static("value")); let client = reqwest::blocking::Client::builder() .user_agent("Rust-test") .default_headers(default_headers) .build()?; // Headers for this request only let mut headers = header::HeaderMap::new(); headers.insert( reqwest::header::CONTENT_TYPE, header::HeaderValue::from_static("image/png"), ); let response = client.get(url) .headers(headers) .bearer_auth("DEadBEEfc001cAFeEDEcafBAd") // Enable HTTP bearer authentication. .send()?; assert_eq!( response.url().as_str(), "http://httpbin.org/headers?lang=rust&browser=servo" ); let out: HeadersEcho = response.json()?; assert_eq!( out.headers["Authorization"], "Bearer DEadBEEfc001cAFeEDEcafBAd" ); assert_eq!(out.headers["User-Agent"], "Rust-test"); assert_eq!(out.headers["X-My-Header"], "value"); println!("{:?}", out); Ok(()) }