推荐答案
// www.javascriptcn.com code example
use reqwest::blocking::get;
use reqwest::Error;
fn main() -> Result<(), Error> {
let url = "https://api.example.com/data";
let response = get(url)?;
if response.status().is_success() {
let body = response.text()?;
println!("Response body: {}", body);
} else {
println!("Request failed with status: {}", response.status());
}
Ok(())
}本题详细解读
1. 引入 reqwest 库
首先,需要在 Cargo.toml 文件中添加 reqwest 依赖:
[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }2. 使用 reqwest::blocking::get 发送 GET 请求
reqwest::blocking::get 是一个同步的 HTTP GET 请求方法。它接受一个 URL 字符串作为参数,并返回一个 Result<Response, Error>。
let response = get(url)?;
3. 处理响应
通过 response.status() 可以获取 HTTP 响应的状态码。is_success() 方法用于判断请求是否成功(状态码为 2xx)。
if response.status().is_success() {
let body = response.text()?;
println!("Response body: {}", body);
} else {
println!("Request failed with status: {}", response.status());
}4. 处理错误
reqwest 使用 Result 类型来处理可能的错误。通过 ? 操作符可以将错误向上传播,或者在 main 函数中返回 Result<(), Error> 来处理错误。
fn main() -> Result<(), Error> {
// ...
Ok(())
}5. 异步请求
如果需要发送异步请求,可以使用 reqwest 的异步 API。首先需要在 Cargo.toml 中启用 tokio 运行时:
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }然后使用 reqwest::get 发送异步请求:
// www.javascriptcn.com code example
use reqwest::Error;
#[tokio::main]
async fn main() -> Result<(), Error> {
let url = "https://api.example.com/data";
let response = reqwest::get(url).await?;
if response.status().is_success() {
let body = response.text().await?;
println!("Response body: {}", body);
} else {
println!("Request failed with status: {}", response.status());
}
Ok(())
}6. 其他 HTTP 方法
reqwest 还支持其他 HTTP 方法,如 POST、PUT、DELETE 等。可以通过 reqwest::blocking::Client 或 reqwest::Client 来构建请求:
// www.javascriptcn.com code example
use reqwest::blocking::Client;
use reqwest::Error;
fn main() -> Result<(), Error> {
let client = Client::new();
let response = client.post("https://api.example.com/data")
.body("data")
.send()?;
if response.status().is_success() {
let body = response.text()?;
println!("Response body: {}", body);
} else {
println!("Request failed with status: {}", response.status());
}
Ok(())
}