91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

rust reqwest有哪些常見用法

小樊
81
2024-11-21 17:16:39
欄目: 編程語言

reqwest 是一個用于 Rust 的強大 HTTP 客戶端庫,它允許你輕松地進行 HTTP 請求。以下是 reqwest 的一些常見用法:

  1. 發送 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)
}
  1. 發送 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)
}
  1. 添加請求頭:
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)
}
  1. 超時設置:
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)
}
  1. 錯誤處理:
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),
    }
}
  1. 同步請求(不推薦):
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 方法、處理響應數據等。

0
二连浩特市| 抚顺市| 永和县| 河源市| 北碚区| 鄢陵县| 大田县| 家居| 兖州市| 弋阳县| 赞皇县| 襄城县| 淳化县| 灵璧县| 武宣县| 千阳县| 忻州市| 安平县| 通河县| 岱山县| 措勤县| 疏勒县| 都兰县| 佛坪县| 电白县| 上思县| 沛县| 呼和浩特市| 迁西县| 科技| 沂源县| 高雄县| 浠水县| 曲松县| 宿州市| 洱源县| 通化县| 南安市| 砚山县| 达拉特旗| 德清县|