下载 zip 文件

问题描述 投票:0回答:1

我正在尝试使用 Rust 从澳大利亚统计局下载 zip 文件。

以下 python 代码运行良好。

import requests

def example():
    url = (
        "http://www.abs.gov.au/statistics/economy/price-indexes-and-inflation/"
        "monthly-consumer-price-index-indicator/dec-2023/All-Time-Series-Spreadsheets.zip"
    ) 
    response = requests.get(url, allow_redirects=True, stream=True, timeout=20)  
    if response.status_code == 200 and response.headers is not None:
        size = sum(len(chunk) for chunk in response.iter_content(8196))
        print(size)

example()  # prints 127525 (bytes)

但是,当我在 Rust 中尝试类似的东西时(并且我尝试了一些不同的板条箱),我无法让它工作。示例代码如下。

fn example() {
    let url = concat!(
        "http://www.abs.gov.au/statistics/economy/price-indexes-and-inflation/",
        "monthly-consumer-price-index-indicator/dec-2023/All-Time-Series-Spreadsheets.zip"
    );
    let client = reqwest::blocking::Client::new();
    let zip_bytes = client
        .get(url)
        .send().unwrap()
        .bytes().unwrap();
    println!("Length: {}", zip_bytes.len());
}

example()  // prints 70 
rust download
1个回答
0
投票

您可能正在打印响应标头的长度。以下代码应获取 url 并将其保存到标题为

All-Time-Series-Spreadsheets.zip

的文件中

您确实应该使用

https
而不是
http
,以防止中间人攻击之类的事情。

fn example() {
    let url = concat!(
        "https://www.abs.gov.au/statistics/economy/price-indexes-and-inflation/",
        "monthly-consumer-price-index-indicator/dec-2023/All-Time-Series-Spreadsheets.zip"
    );
    let resp = reqwest::blocking::get(url).expect("request failed");
    let body = resp.bytes().expect("body invalid");
    std::fs::write("./All-Time-Series-Spreadsheets.zip", &body);
}

example()
© www.soinside.com 2019 - 2024. All rights reserved.