阅读量:2
reqwest 是一个用于 Rust 的强大 HTTP 客户端库,它允许你轻松地进行 HTTP 请求。以下是 reqwest 的一些常见用法:
- 发送 GET 请求:
use reqwest::Error;
async fn get_request() -> Result<String, Error> {
let response = reqwest::get("https://api.example.com/data")
.await?
.text()
.await?;
Ok(response)
}
- 发送 POST 请求:
use reqwest::{Client, Error};
use serde_json::json;
async fn post_request() -> Result<String, Error> {
let client = Client::new();
let data = json!({
"key": "value",
});
let response = client.post("https://api.example.com/data")
.json(&data)
.send()
.await?
.text()
.await?;
Ok(response)
}
- 添加请求头:
use reqwest::Error;
async fn request_with_headers() -> Result<String, Error> {
let client = Client::new();
let response = client.get("https://api.example.com/data")
.header("Authorization", "Bearer your_token")
.header("Custom-Header", "custom_value")
.send()
.await?
.text()
.await?;
Ok(response)
}
- 超时设置:
use reqwest::Error;
use std::time::Duration;
async fn request_with_timeout() -> Result<String, Error> {
let client = Client::builder()
.timeout(Duration::from_secs(5))
.build()?;
let response = client.get("https://api.example.com/data")
.send()
.await?
.text()
.await?;
Ok(response)
}
- 错误处理:
use reqwest::Error;
async fn handle_error() {
match reqwest::get("https://api.example.com/data")
.await
{
Ok(response) => {
if response.status().is_success() {
let body = response.text().await?;
println!("Success! Body: {}", body);
} else {
eprintln!("Error: {}", response.status());
}
}
Err(e) => eprintln!("Request failed: {}", e),
}
}
- 同步请求(不推荐):
use reqwest::Error;
fn sync_request() -> Result<String, Error> {
let response = reqwest::get("https://api.example.com/data")
.send()?
.text()?;
Ok(response)
}
这些示例展示了如何使用 reqwest 库执行基本的 HTTP 请求。你可以根据自己的需求进行调整,例如使用不同的 HTTP 方法、处理响应数据等。
以上就是关于“rust reqwest有哪些常见用法”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm