Rust HTTP请求库http-request的使用,高效处理HTTP客户端请求与响应

Rust HTTP请求库http-request的使用,高效处理HTTP客户端请求与响应

http-request是一个轻量级、高效的Rust库,用于构建、发送和处理HTTP/HTTPS请求。它提供了简单直观的API,支持HTTP/HTTPS协议、WebSocket、自定义请求头、请求体、超时设置、自动重定向处理等功能。

特性

  • 支持HTTP/HTTPS:支持HTTP和HTTPS协议
  • WebSocket支持:提供同步和异步API的完整WebSocket支持
  • 轻量设计:提供简单高效的API,同时最小化资源消耗
  • 支持常见HTTP方法:支持GET、POST等常见HTTP方法
  • 灵活的请求构建:通过RequestBuilder提供丰富的配置选项
  • 简单的错误处理:使用Result类型处理请求和响应中的错误
  • 自定义请求头和请求体:可以轻松添加自定义请求头和请求体
  • 响应处理:提供对HTTP响应的简单包装
  • 优化的内存管理:实现高效的内存管理以最小化不必要的内存分配
  • 重定向处理:支持重定向处理,包括设置最大重定向次数和检测重定向循环
  • 超时设置:支持超时设置
  • 响应体解码:支持自动和手动解码响应体
  • 代理支持:全面的代理支持,包括HTTP、HTTPS和SOCKS5代理

安装

在项目目录中运行以下Cargo命令:

cargo add http-request

或在Cargo.toml中添加:

http-request = "8.91.6"

完整示例代码

以下是一个综合使用http-request库的完整示例,展示同步和异步HTTP请求以及WebSocket连接:

use http_request::*;
use tokio; // 用于异步运行时

fn main() {
    // 同步HTTP请求示例
    sync_http_example();
    
    // 异步HTTP请求示例
    tokio::runtime::Runtime::new().unwrap().block_on(async {
        async_http_example().await;
    });
    
    // WebSocket示例
    websocket_example();
}

// 同步HTTP请求示例
fn sync_http_example() {
    println!("=== 同步HTTP请求示例 ===");
    
    // GET请求示例
    let mut headers = hash_map_xx_hash3_64();
    headers.insert("User-Agent", "http-request-example");
    
    let get_request = RequestBuilder::new()
        .get("https://httpbin.org/get")  // 设置GET方法和URL
        .headers(headers)                // 添加请求头
        .timeout(5000)                   // 设置超时时间(毫秒)
        .redirect()                      // 启用重定向
        .max_redirect_times(5)           // 最大重定向次数
        .build_sync();                   // 构建同步请求
        
    match get_request.send() {
        Ok(response) => {
            println!("GET响应状态: {}", response.status());
            println!("GET响应内容: {}", response.text().unwrap_or_default());
        }
        Err(e) => eprintln!("GET请求错误: {}", e),
    }
    
    // POST请求示例(JSON)
    let mut post_headers = hash_map_xx_hash3_64();
    post_headers.insert("Content-Type", "application/json");
    
    let json_body = json_value!({
        "name": "Rust",
        "version": "1.70.0",
        "features": ["performance", "safety"]
    });
    
    let post_request = RequestBuilder::new()
        .post("https://httpbin.org/post") // 设置POST方法和URL
        .json(json_body)                 // 设置JSON请求体
        .headers(post_headers)           // 添加请求头
        .timeout(5000)                   // 设置超时时间
        .build_sync();                   // 构建同步请求
        
    match post_request.send() {
        Ok(response) => {
            println!("POST响应状态: {}", response.status());
            println!("POST响应内容: {}", response.text().unwrap_or_default());
        }
        Err(e) => eprintln!("POST请求错误: {}", e),
    }
}

// 异步HTTP请求示例
async fn async_http_example() {
    println!("\n=== 异步HTTP请求示例 ===");
    
    let mut headers = hash_map_xx_hash3_64();
    headers.insert("User-Agent", "async-http-request");
    headers.insert("Accept", "application/json");
    
    let request = RequestBuilder::new()
        .get("https://httpbin.org/headers")  // 获取请求头信息的API
        .headers(headers)                   // 添加自定义请求头
        .timeout(3000)                      // 设置超时时间
        .build_async();                     // 构建异步请求
        
    match request.send().await {
        Ok(response) => {
            println!("异步请求响应状态: {}", response.status());
            println!("异步请求响应内容: {}", response.text());
        }
        Err(e) => eprintln!("异步请求错误: {}", e),
    }
}

// WebSocket示例
fn websocket_example() {
    println!("\n=== WebSocket示例 ===");
    
    let mut headers = hash_map_xx_hash3_64();
    headers.insert("Authorization", "Bearer test-token-123");
    
    let mut websocket = WebSocketBuilder::new()
        .connect("ws://echo.websocket.org")  // WebSocket测试服务器
        .headers(headers)                   // 添加请求头
        .timeout(10000)                     // 设置超时时间
        .buffer(4096)                       // 设置缓冲区大小
        .protocols(&["rust-protocol"])      // 设置子协议
        .build_sync();                      // 构建同步WebSocket连接
        
    // 发送文本消息
    websocket.send_text("Hello WebSocket from Rust!")
        .and_then(|_| {
            println!("已发送文本消息");
            // 接收消息
            match websocket.receive() {
                Ok(message) => match message {
                    WebSocketMessage::Text(text) => println!("收到文本消息: {}", text),
                    WebSocketMessage::Binary(data) => println!("收到二进制消息: {:?}", data),
                    WebSocketMessage::Close => println!("连接关闭"),
                    _ => println!("收到其他类型消息"),
                },
                Err(e) => println!("接收消息错误: {}", e),
            }
            Ok(())
        })
        .and_then(|_| websocket.close())  // 关闭连接
        .unwrap_or_else(|e| println!("WebSocket错误: {}", e));
}

要运行这个示例,需要在Cargo.toml中添加以下依赖:

[dependencies]
http-request = "8.91.6"
tokio = { version = "1", features = ["full"] }

示例说明

  1. 同步HTTP请求

    • 展示了GET和POST请求的基本用法
    • 包含请求头设置、超时设置和重定向配置
    • 演示了JSON请求体的发送方式
  2. 异步HTTP请求

    • 使用tokio运行时执行异步请求
    • 展示了异步API的基本用法
  3. WebSocket连接

    • 展示了如何建立WebSocket连接
    • 演示了文本消息的发送和接收
    • 包含错误处理和连接关闭

许可证

该项目使用MIT许可证。


1 回复

Rust HTTP请求库http-request的使用指南

简介

http-request 是一个轻量级、高效的Rust HTTP客户端库,专为简化HTTP请求处理而设计。它提供了简洁的API来处理各种HTTP请求和响应,支持异步操作,适合构建需要高性能HTTP通信的Rust应用。

安装

在Cargo.toml中添加依赖:

[dependencies]
http-request = "0.7"

基本使用方法

1. 发送GET请求

use http_request::get;

#[tokio::main]
async fn main() -> Result<(), http_request::Error> {
    // 发送GET请求并等待响应
    let response = get("https://httpbin.org/get").send().await?;
    
    // 打印响应状态码和正文
    println!("Status: {}", response.status());
    println!("Body: {}", response.text().await?);
    
    Ok(())
}

2. 发送POST请求

use http_request::post;

#[tokio::main]
async fn main() -> Result<(), http_request::Error> {
    // 发送POST请求并附带正文
    let response = post("https://httpbin.org/post")
        .body("Hello, World!")
        .send()
        .await?;
    
    // 打印响应正文
    println!("Response: {}", response.text().await?);
    
    Ok(())
}

3. 设置请求头

use http_request::get;

#[tokio::main]
async fn main() -> Result<(), http_request::Error> {
    // 发送GET请求并设置自定义请求头
    let response = get("https://httpbin.org/headers")
        .header("X-Custom-Header", "RustIsAwesome")
        .send()
        .await?;
    
    // 打印响应正文
    println!("Response: {}", response.text().await?);
    
    Ok(())
}

高级功能

1. 处理JSON数据

use http_request::post;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), http_request::Error> {
    // 创建JSON数据
    let data = json!({
        "name": "Rustacean",
        "age": 5,
        "skills": ["ownership", "borrowing", "fearless"]
    });

    // 发送POST请求并附带JSON数据
    let response = post("https://httpbin.org/post")
        .json(&data)?
        .send()
        .await?;
    
    // 打印响应正文
    println!("Response: {}", response.text().await?);
    
    Ok(())
}

2. 处理查询参数

use http_request::get;

#[tokio::main]
async fn main() -> Result<(), http_request::Error> {
    // 发送GET请求并添加查询参数
    let response = get("https://httpbin.org/get")
        .query(&[("page", "2"), ("limit", "20")])
        .send()
        .await?;
    
    // 打印响应正文
    println!("Response: {}", response.text().await?);
    
    Ok(())
}

3. 超时设置

use http_request::get;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), http_request::Error> {
    // 发送GET请求并设置3秒超时
    let response = get("https://httpbin.org/delay/5")
        .timeout(Duration::from_secs(3))
        .send()
        .await?;
    
    // 打印响应正文
    println!("Response: {}", response.text().await?);
    
    Ok(())
}

错误处理

http-request 提供了详细的错误类型:

use http_request::{get, Error};

#[tokio::main]
async fn main() {
    // 匹配不同的错误类型
    match get("https://invalid.url").send().await {
        Ok(response) => println!("Success: {}", response.status()),
        Err(Error::Network(e)) => eprintln!("Network error: {}", e),
        Err(Error::InvalidUrl(e)) => eprintln!("Invalid URL: {}", e),
        Err(Error::Timeout) => eprintln!("Request timed out"),
        Err(e) => eprintln!("Other error: {}", e),
    }
}

性能优化技巧

  1. 重用Client实例:对于多个请求,创建并重用Client实例可以提高性能
use http_request::Client;

#[tokio::main]
async fn main() -> Result<(), http_request::Error> {
    // 创建Client实例
    let client = Client::new();
    
    // 重用Client发送多个请求
    let response1 = client.get("https://httpbin.org/get").send().await?;
    let response2 = client.post("https://httpbin.org/post").send().await?;
    
    // 处理响应...
    
    Ok(())
}
  1. 流式处理大响应:对于大文件或流数据,使用stream()方法
use http_request::get;
use futures::StreamExt;

#[tokio::main]
async fn main() -> Result<(), http_request::Error> {
    // 获取响应流
    let mut stream = get("https://example.com/large-file")
        .send()
        .await?
        .stream();
    
    // 逐块处理数据
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        // 处理数据块
    }
    
    Ok(())
}

完整示例

use http_request::{get, post, Client};
use serde_json::json;
use std::time::Duration;
use futures::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. 基本GET请求
    println!("--- 基本GET请求 ---");
    let response = get("https://httpbin.org/get").send().await?;
    println!("Status: {}", response.status());
    println!("Body: {}\n", response.text().await?);

    // 2. POST请求与JSON处理
    println!("--- POST请求与JSON处理 ---");
    let data = json!({
        "name": "Rustacean",
        "age": 5
    });
    let json_response = post("https://httpbin.org/post")
        .json(&data)?
        .send()
        .await?;
    println!("JSON Response: {}\n", json_response.text().await?);

    // 3. 客户端重用
    println!("--- 客户端重用 ---");
    let client = Client::new();
    let client_response1 = client.get("https://httpbin.org/get").send().await?;
    let client_response2 = client.post("https://httpbin.org/post").send().await?;
    println!("Client Response 1 Status: {}", client_response1.status());
    println!("Client Response 2 Status: {}\n", client_response2.status());

    // 4. 流式处理
    println!("--- 流式处理 ---");
    let mut stream = get("https://httpbin.org/stream/3")
        .send()
        .await?
        .stream();
    
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        println!("Received chunk: {}", String::from_utf8_lossy(&chunk));
    }

    Ok(())
}

总结

http-request 提供了简单直观的API来处理HTTP请求,同时保持了高性能。它的设计哲学是提供必要的功能而不增加不必要的复杂性,非常适合需要高效HTTP通信的Rust项目。

回到顶部