Rust: Making a HTTP POST request (with parameters)
Mar 24, 2022
This one proved to be a little easier given we'd established all of the foundations with a get request:
use hyper::{Body, Method, Client, Request};
use hyper::body::HttpBody as _;
use tokio::io::{stdout, AsyncWriteExt as _};
use url::form_urlencoded;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let params = vec![("foo", "bar")];
let body = form_urlencoded::serialize(params.into_iter());
let client = Client::new();
let req = Request::builder()
.method(Method::POST)
.uri("http://httpbin.org/post")
.body(body)?;
let mut resp = client.request(req).await?;
println!("Response: {}", resp.status());
while let Some(chunk) = resp.body_mut().data().await {
stdout().write_all(&chunk?).await?;
}
Ok(())
}
We've had to unravel the previous get()
request into two parts now: 1) building out the request objects and then 2) passing the request into the client to execute it. Adding on to that Request::builder
is how and where we'd add additional headers or otherwise manipulate the request before sending it.
Hi, I'm Glenn! 👋 I'm currently Director of Product (Terraform) @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product Management, Design, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.