make a http request with a custom body as form url encoded in rust

To make an HTTP request with a custom body as form url encoded in Rust, you can use the http crate which provides convenient methods for constructing HTTP requests. First, add the following to your Cargo.toml file to include the http crate as a dependency:

[dependencies]
http = "0.2"
28 chars
3 lines

Then, you can make the HTTP request using the following code:

main.rs
use http::request::Builder;
use http::{Request, StatusCode};

fn make_request(url: &str, form_data: &[(&str, &str)]) -> Result<(), String> {
    let client = reqwest::blocking::Client::new();
    
    let req_builder: Builder = Request::builder()
        .method("POST")
        .uri(url)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body(
            form_data
                .iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect::<Vec<_>>()
                .join("&"),
        )
        .unwrap();

    let resp = client.execute(req_builder.body(None).unwrap())?;

    if resp.status() == StatusCode::OK {
        let body = resp.text()?;
        // Do something with the response body
        Ok(())
    } else {
        Err(format!("failed request with status code {}", resp.status()))
    }
}
865 chars
30 lines

In the above code, the make_request function takes in a URL and an array of key-value pairs representing the data to be sent in the form. The function constructs a POST request, sets the Content-Type header to application/x-www-form-urlencoded, and constructs the request body by concatenating the key-value pairs with & characters as separators. The resulting request is then sent using the reqwest crate, and the function returns the response body if the request is successful, or an error message if it fails.

gistlibby LogSnag