make a http request with a custom body as text in rust

To make an HTTP request with a custom body as text in Rust, you can use the reqwest crate. Here's an example:

main.rs
use reqwest::StatusCode;

fn main() -> Result<(), reqwest::Error> {
    let client = reqwest::blocking::Client::new();
    let response = client
        .post("https://httpbin.org/post")
        .body("Hello, world!")
        .send()?;
    if response.status() == StatusCode::OK {
        println!("Request succeeded!");
    }
    Ok(())
}
340 chars
14 lines

In this example, we create an instance of the Client struct from reqwest::blocking and then use its post method to specify the URL we want to send the request to. We set the body of the request to "Hello, world!" by using the body method.

This example sends a blocking HTTP request and prints "Request succeeded!" if the response is HTTP status code 200 (OK). If the response is not successful, an error will be returned.

Note that this code uses Rust's Result type to handle errors. The ? operator is used to propagate errors up the call stack. The reqwest::Error type is used for all errors related to the reqwest crate.

related categories

gistlibby LogSnag