【问题标题】:Why do the bytes of a PNG image downloaded with reqwest differ from those downloaded with Python?为什么使用 reqwest 下载的 PNG 图像的字节数与使用 Python 下载的字节数不同?
【发布时间】:2020-12-20 23:40:48
【问题描述】:

我正在尝试使用 reqwest 库来下载 PNG 文件,但是当我下载它时,我看到一个奇怪的行为,尊重其他编程语言,例如:Python。

例如:

let content = reqwest::get("https://www.google.es/images/searchbox/desktop_searchbox_sprites302_hr.png").await?;

如果我将结果打印为字节数组 (println!("{:?}", content.text().await?.as_bytes());

[ 191, 189, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 40, 0, 0, 0, 82, 8, 3, 0, 0, 0, 17,  191, 189, 102,  191, 189, 0, 0, 0, 108, 80, 76, 84, 69, 0, 0, 0,  191, 189,  191, 189,  191, 189,...]

但是,使用 Python 请求的结果是:

[137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 40, 0, 0, 0, 82, 8, 3, 0, 0, 0, 17, 153, 102, 248, ...]

在 Rust 版本中,我看到了很多 191, 189。这个序列在整个数组中重复了很多次,但在 Python 中根本不会出现。

我在 Rust 中做错了什么?

【问题讨论】:

  • 很难回答您的问题,因为它不包含minimal reproducible example。我们无法分辨代码中存在哪些 crate(及其版本)、类型、特征、字段等。如果您尝试在 Rust Playground 上重现您的错误,如果可能的话,这将使我们更容易为您提供帮助,否则在全新的 Cargo 项目中,然后在 edit 您的问题中包含附加信息。您可以使用Rust-specific MRE tips 来减少您在此处发布的原始代码。谢谢!

标签: arrays rust binary reqwest


【解决方案1】:

我看到很多191, 189

最好看成EF, BF, BD,也就是Unicode replacement character编码为UTF-8。二进制数据不是文本数据。二进制数据不应使用text,而应使用bytes

const URL: &str = "https://www.google.es/images/searchbox/desktop_searchbox_sprites302_hr.png";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let content = reqwest::get(URL).await?;
    let bytes = content.bytes().await?;
    println!("{:x?}", &bytes[..]);

    Ok(())
}
[89, 50, 4e, 47, d, a, 1a, a, 0, 0, 0, d, 49, 48, 44, 52, 0, 0, 0, 28, 0, 0, 0, 52, 8, 3, 0, 0, 0, 11, 99, 66, f8, 0, 0, 0, 6c, 50, 4c, 54, 45, 0, 0, 0, 9f, ...

【讨论】:

  • 非常感谢您的帮助。这个答案帮助我解决了这个问题。当我查看 reqwest 文档时,我没有看到方法 bytes() ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-13
相关资源
最近更新 更多