make a http request with a custom header in rust

To make an HTTP request with a custom header in Rust, you can use the hyper crate, which is a fast and low-level HTTP implementation in Rust.

Here is an example code snippet on how to make a GET request with a custom header using hyper:

main.rs
extern crate hyper;

use hyper::{Client, Request, body::HttpBody, header};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Create a new HTTP client
    let client = Client::new();

    // Create a GET request with custom header
    let mut request = Request::builder()
        .uri("https://example.com")
        .header(header::USER_AGENT, "my-awesome-app")
        .body(hyper::Body::empty())
        .unwrap();

    // Send the request and await the response
    let response = client.request(request).await?;

    // Read the response body
    let mut response_body = String::new();
    let mut stream = response.into_body();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        let chunk_str = std::str::from_utf8(&chunk)?;
        response_body.push_str(chunk_str);
    }

    println!("{}", response_body);

    Ok(())
}
910 chars
33 lines

In this example, we created a new HTTP client using the Client::new() method. Then we created a GET request with a custom User-Agent header using the Request::builder() method and the header::USER_AGENT constant from the hyper::header module. Afterward, we sent the request using the client.request(request).await? method, which returns a response. Finally, we read the response body using a hyper::Body stream and printed it out.

related categories

gistlibby LogSnag