Invio richieste HTTP in Rust con hyper

Mattepuffo's logo
Invio richieste HTTP in Rust con hyper

Invio richieste HTTP in Rust con hyper

hyper una libreria per Rust per la creazione sia di un server che di un client HTTP.

In questo articolo vediamo come usarla per eseguire richieste HTTP; siccome al giorno d'oggi le richieste passano tutte per HTTPS, installeremo anche hyper-tls.

Queste tutte le dipendenze che ci servono:

[dependencies]
hyper = { version = "0.14.23", features = ["full"] }
tokio = { version = "1.23.0", features = ["full"] }
hyper-tls = "0.5.0"

Qui sotto un esempio di codice:

use hyper::body::HttpBody;
use hyper::Client;
use hyper_tls::HttpsConnector;
use tokio::io::{stdout, AsyncWriteExt as _};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "https://jsonplaceholder.typicode.com/todos/1".parse()?;

    let https = HttpsConnector::new();
    let client = Client::builder()
        .build::<_, hyper::Body>(https);

    let mut resp = client.get(url).await?;

    println!("Response: {}", resp.status());

    while let Some(chunk) = resp.body_mut().data().await {
        stdout().write_all(&chunk?).await?;
    }

    Ok(())
}

Non facciamo il parsing del JSON, che richiede anche tutta una serie di considerazione.

Ma il body che riceviamo è il JSON che ci viene restituito dall'API.

Enjoy!


Condividi

Commentami!