DEV Community

Bruno Barros
Bruno Barros

Posted on

Chamada HTTP em Rust

Para fazer uma chamada HTTP em Rust, você pode usar a biblioteca reqwest. Você pode adicioná-la como uma dependência no seu arquivo Cargo.toml:

[dependencies]
reqwest = "0.10.8"
Enter fullscreen mode Exit fullscreen mode

Em seguida, você pode importá-la no seu código e usá-la para fazer uma chamada HTTP. Aqui está um exemplo de como fazer uma chamada GET simples para a URL "https://www.example.com":

extern crate reqwest;

fn main() {
    let res = reqwest::get("https://www.example.com")
        .expect("Falha ao fazer a chamada HTTP");
    println!("Status: {}", res.status());

    let body = res.text().expect("Falha ao ler o corpo da resposta");
    println!("Corpo: {}", body);
}

Enter fullscreen mode Exit fullscreen mode

Isso faz uma chamada GET para a URL "https://www.example.com" e imprime o status da resposta e o corpo da resposta.

Você também pode fazer chamadas HTTP usando outros métodos, como POST, PUT e DELETE. Aqui está um exemplo de como fazer uma chamada POST com um corpo de solicitação JSON:

extern crate reqwest;
extern crate serde_json;

use serde_json::Value;

fn main() {
    let client = reqwest::Client::new();

    let mut json = Value::new_object();
    json.insert("name".to_string(), Value::from("John"));
    json.insert("age".to_string(), Value::from(30));

    let res = client.post("https://www.example.com/api/users")
        .json(&json)
        .send()
        .expect("Falha ao fazer a chamada HTTP");

    println!("Status: {}", res.status());
}

Enter fullscreen mode Exit fullscreen mode

*** post gerado via AI e revisado por mim.**

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️