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(())
}
相关推荐
yuanbenshidiaos3 分钟前
c++------------------函数
开发语言·c++
程序员_三木15 分钟前
Three.js入门-Raycaster鼠标拾取详解与应用
开发语言·javascript·计算机外设·webgl·three.js
是小崔啊25 分钟前
开源轮子 - EasyExcel01(核心api)
java·开发语言·开源·excel·阿里巴巴
tianmu_sama31 分钟前
[Effective C++]条款38-39 复合和private继承
开发语言·c++
黄公子学安全34 分钟前
Java的基础概念(一)
java·开发语言·python
liwulin050635 分钟前
【JAVA】Tesseract-OCR截图屏幕指定区域识别0.4.2
java·开发语言·ocr
jackiendsc39 分钟前
Java的垃圾回收机制介绍、工作原理、算法及分析调优
java·开发语言·算法
Yuan_o_40 分钟前
Linux 基本使用和程序部署
java·linux·运维·服务器·数据库·后端
Oneforlove_twoforjob43 分钟前
【Java基础面试题027】Java的StringBuilder是怎么实现的?
java·开发语言
羚羊角uou1 小时前
【C++】优先级队列以及仿函数
开发语言·c++