make a http request with a custom body as form data in rust

To make a HTTP request with a custom body as form data in Rust, you can use the reqwest crate, which provides a convenient API for sending HTTP requests. Here's an example code snippet that demonstrates how to make a POST request with form data using reqwest:

main.rs
use std::collections::HashMap;

use reqwest::blocking::Client;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a new HTTP client
    let client = Client::new();

    // Define the path and data to be sent in the request
    let path = "https://example.com/api/endpoint";
    let mut data = HashMap::new();
    data.insert("param1", "value1");
    data.insert("param2", "value2");

    // Send the POST request with form data
    let response = client
        .post(path)
        .form(&data)
        .send()?;

    // Print the response body
    println!("{}", response.text()?);

    Ok(())
}
615 chars
26 lines

In this code, we first create a new Client object from the reqwest crate. Then, we define the path where the request will be sent, and construct a HashMap with the form data to be sent in the request.

Finally, we use the post() method to create a POST request, and chain the form() method to add the form data to the request body. The send() method is used to actually send the request, and the response is stored in the response variable.

Note: The blocking module is used here for simplicity, but in real applications you should use the non-blocking asynchronous API (which is more performant).

gistlibby LogSnag