reqwest - Rust HTTP Client

发布于:2024-05-16 ⋅ 阅读:(38) ⋅ 点赞:(0)


关于 reqwest

An easy and powerful Rust HTTP Client


特点

  • Async and blocking Clients
  • Plain bodies, JSON, urlencoded, multipart
  • Customizable redirect policy
  • HTTP Proxies
  • HTTPS via system-native TLS (or optionally, rustls)
  • Cookie Store
  • WASM

使用

添加依赖

Cargo.toml 文件的 [dependencies] 下添加代码:


reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["full"] }

Get 请求

// 一个普通请求
let body = reqwest::get("https://www.rust-lang.org")
              .await?
              .text()
              .await?;

println!("body = {body:?}");

Post 请求

你可以使用 RequestBuilder 设置请求体,也可以使用 reqwest::Body 构造器

let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
    .body("the exact body that is sent")
    .send()
    .await?;

Forms

// This will POST a body of `foo=bar&baz=quux`
let params = [("foo", "bar"), ("baz", "quux")];
let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
    .form(&params)
    .send()
    .await?;

JSON

// This will POST a body of `{"lang":"rust","body":"json"}`
let mut map = HashMap::new();
map.insert("lang", "rust");
map.insert("body", "json");

let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
    .json(&map)
    .send()
    .await?;

伊织 2024-05-09(四)

吃自己做的炸鸡米花