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.**

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay