make a http request with a custom body as binary and return a binary response in rust

To make a HTTP request with a custom body as binary and return a binary response in Rust, you can use the reqwest crate. Here is an example:

main.rs
use reqwest::blocking::Client;
use std::io::Read;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Customize this as needed
    let url = "https://example.com/api/endpoint";
    let body: Vec<u8> = vec![0x01, 0x02, 0x03];

    // Create a HTTP client
    let client = Client::new();

    // Create a HTTP request with a binary body
    let request = client.post(url).body(body);

    // Send the request and get the response
    let mut response = request.send()?;

    // Read the response body into a binary buffer
    let mut buffer = Vec::new();
    response.read_to_end(&mut buffer)?;

    // Do something with the response body
    println!("{:?}", buffer);

    Ok(())
}
691 chars
27 lines

In this example, we first define the URL we want to make a request to and the binary data we want to send in the body.

Next, we create a Client object from the reqwest crate which we'll use to send the request.

We then create a POST request using the post method on our client object and provide our URL as an argument.

We include the binary data we want to send in the body of the request using the body method.

We send the request using the send method on our request object and store the response in a variable called response.

We create an empty vector called buffer to read the response body into.

Finally, we read the response body into the buffer vector using the read_to_end method on the response object.

At this point, the buffer vector contains the binary response returned by the server. We can do whatever we want with it, such as parsing it or writing it to a file.

gistlibby LogSnag