使用Rust的reqwest库发送HTTP请求的示例代码

我正在学习使用Rust的reqwest库发送HTTP请求,但遇到了一些问题。请问能否提供一个完整的示例代码,展示如何发送GET和POST请求?最好能包含设置请求头、处理响应和错误处理的完整示例。另外,如果想发送JSON数据或表单数据,代码应该怎么写?谢谢!

2 回复

使用reqwest库发送GET请求的示例:

use reqwest;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let response = reqwest::get("https://httpbin.org/ip").await?;
    let body = response.text().await?;
    println!("响应内容: {}", body);
    Ok(())
}

需要在Cargo.toml中添加依赖:

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

以下是使用 Rust 的 reqwest 库发送 HTTP 请求的示例代码。首先,确保在 Cargo.toml 中添加依赖:

[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }
tokio = { version = "1", features = ["full"] }

1. 同步(阻塞)GET 请求示例

use reqwest;

fn main() -> Result<(), reqwest::Error> {
    let response = reqwest::blocking::get("https://httpbin.org/ip")?;
    let body = response.text()?;
    println!("响应内容: {}", body);
    Ok(())
}

2. 异步 GET 请求示例

use reqwest;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let response = reqwest::get("https://httpbin.org/ip").await?;
    let body = response.text().await?;
    println!("响应内容: {}", body);
    Ok(())
}

3. 带自定义请求头的 POST 请求示例

use reqwest;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = reqwest::Client::new();
    let response = client
        .post("https://httpbin.org/post")
        .header("User-Agent", "MyRustApp/1.0")
        .body("Hello, World!")
        .send()
        .await?;
    
    println!("状态码: {}", response.status());
    let body = response.text().await?;
    println!("响应内容: {}", body);
    Ok(())
}

说明:

  • 同步请求:使用 reqwest::blocking 模块,适用于简单脚本或不需要高并发的场景。
  • 异步请求:需启用 tokio 运行时,使用 async/await 语法,适合高性能应用。
  • 错误处理通过 ? 操作符简化,返回 reqwest::Error

运行前请通过 cargo build 确保依赖正确安装。

回到顶部