Rust: reqwest库示例

一、异步处理单任务

1、cargo.toml

复制代码
[dependencies]
tokio = { version = "1.0.0",  features = ["full", "tracing"] }
tokio-util = { version = "0.7.0",  features = ["full"] }
tokio-stream = { version = "0.1"  }

tracing = "0.1"
tracing-subscriber = { version = "0.3.1", default-features = false, features = ["fmt", "ansi", "env-filter", "tracing-log"] }
bytes = "1.0.0"
futures = { version = "0.3.0", features = ["thread-pool"]}
http = "1.0.0"
serde = "1.0.55"
serde_derive = "1.0"
serde_json = "1.0"
httparse = "1.0"
httpdate = "1.0"
once_cell = "1.5.2"
rand = "0.8.3"
csv = "1.3.0"
encoding= "0.2.33"
reqwest = { version = "0.11", features = ["json"] }

主要看tokio和reqwest设置就可以了。其它是个人其它的库,没有删除。

2、代码

复制代码
use reqwest::{self};

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let url = "https://vip.stock.finance.sina.com.cn/quotes_service/view/vMS_tradedetail.php?symbol=sz000001";
    let content = reqwest::get(url).await?.text_with_charset("utf-8").await?;
    println!("{content}");
    Ok(())
}

或者

复制代码
use reqwest::{self};
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let url = "https://vip.stock.finance.sina.com.cn/quotes_service/view/vMS_tradedetail.php?symbol=sz000001";
    let _body = reqwest::get(url).await?.text().await?;
    println!("{_body}");
    Ok(())
}

二、异步处理多任务

下面代码参考了

https://blog.csdn.net/wsp_1138886114/article/details/111354010。谨仅参考。

新测是有效的。也可以处理中文字符的问题。

cargo.toml文件,同上。

有异步要爬多个网站的任务,可以参考如下:

相关代码:

复制代码
use tokio;
use futures::future::join_all;

async fn fetch_path(path:String) -> Result<String,reqwest::Error>{
    let mut back_string = String::new();
    match reqwest::get(&path).await {
        Ok(response) => {
            match response.text().await{
                Ok(text) =>{
                    println!("Read response text {},{}" ,text.len(),text);
                    back_string = format!("Read response text {} \t {}\t {}",path,text.len(),text)
                }
                Err(_) => {
                    println!("Read response text Error!")
                }
            };
        }
        Err(_) => {
            println!("reqwest get Error!")
        }
    }
    Ok(back_string)
}

#[tokio::main]
async fn main() -> Result<(),reqwest::Error>{
    let paths = vec![
        "https://www.qq.com.cn".to_string(),
        "https://www.sina.com.cn".to_string(),
        "https://www.sohu.com.cn".to_string()
    ]; 
    let result_list = join_all(paths.into_iter().map(|path|{
        fetch_path(path)
    })).await;

    let mut list_string:Vec<String> = vec![];
    for ele in result_list.into_iter(){
        if ele.is_ok(){
            list_string.push(ele.unwrap())
        }else {
            return Err(ele.unwrap_err())
        }
    }
    println!("请求输出:{:?}",list_string);
    Ok(())
}
相关推荐
踩着两条虫10 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB10 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
Spider Cat 蜘蛛猫10 小时前
Springboot SSO系统设计文档
java·spring boot·后端
即使再小的船也能远航10 小时前
【Python】安装
开发语言·python
Irissgwe10 小时前
类与对象(三)
开发语言·c++·类和对象·友元
雪度娃娃11 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++
zyk_computer11 小时前
AI 时代,或许 Rust 比 Python 更合适
人工智能·后端·python·ai·rust·ai编程·vibe coding
萌新小码农‍12 小时前
python装饰器
开发语言·前端·python
KK溜了溜了12 小时前
Python从入门到精通
服务器·开发语言·python
雨辰AI12 小时前
SpringBoot3 项目国产化改造完整流程|从 MySQL 到人大金仓落地
java·数据库·后端·mysql·政务