首页 > 解决方案 > 如何将网站的内容下载到字符串中?

问题描述

我只想下载一个网站并将其内容放入String.

类似于在 C# 中的操作方式:

WebClient c = new WebClient();
string ex = c.DownloadString("http://url.com");

标签: rust

解决方案


Rust在标准库中没有 HTTP 功能,因此您可能希望使用另一个 crate(库)为您处理 HTTP 内容。为此目的,有几个不同的板条箱。


reqwest: "更高级别的 HTTP 客户端库"

let body = reqwest::get("http://url.com")?.text()?;

ureq: "最小的 HTTP 请求库"

let body = ureq::get("http://url.com").call().into_string()?

isahc:“实用的 HTTP 客户端,使用起来很有趣。”

let mut response = isahc::get("https://example.org")?;
let body = response.text()?;

curl: "Rust 绑定到 libcurl 以发出 HTTP 请求"

use curl::easy::Easy;

// First write everything into a `Vec<u8>`
let mut data = Vec::new();
let mut handle = Easy::new();
handle.url("http://url.com").unwrap();
{
    let mut transfer = handle.transfer();
    transfer.write_function(|new_data| {
        data.extend_from_slice(new_data);
        Ok(new_data.len())
    }).unwrap();
    transfer.perform().unwrap();
}

// Convert it to `String`
let body = String::from_utf8(data).expect("body is not valid UTF8!");

hyper?

Hyper 是一个非常流行的 HTTP 库,但它的级别相当低。这使得它通常太难/太冗长而无法用于小脚本。但是,如果你想编写一个 HTTP 服务器,Hyper 肯定是要走的路(这就是大多数 Rust Web 框架使用 Hyper 的原因)。

好多其它的!

我无法在此答案中列出所有可用的库。因此,请随时搜索 crates.io 以获取更多可以帮助您的 crates。


推荐阅读