我正在try 从澳大利亚统计局下载一个带有Rust的压缩文件.

下面的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中try 类似的东西时(我已经try 了几个不同的 crate ),我无法让它工作.示例代码如下.

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 

推荐答案

您正在下载的网站似乎拒绝(403)个没有User-Agent个HTTP标头的请求.

您可以要求reqwest包括用户代理,如下所示:

fn main() {
    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::ClientBuilder::new()
        .user_agent("reqwest")
        .build()
        .unwrap();
    let zip_bytes = client
        .get(url)
        .send().unwrap()
        .bytes().unwrap();
    println!("Length: {}", zip_bytes.len());
}

Rust相关问答推荐

如何在Rust中为具有多个数据持有者的enum变体编写文档 comments ?

程序退出后只写入指定管道的数据

展开枚举变量并返回所属值或引用

如何将`Join_all``Vec<;Result<;Vec<;Foo&>;,Anywhere::Error&>;`合并到`Result<;Vec<;Foo&>;,Anywhere::Error&>;`

这个规则关于或模式到底是什么意思?如果表达片段的类型与p_i|q_i...&q;不一致,就会形成

编译项目期间使用Cargo生成时出现rustc错误

如何将像烫手山芋一样不透明的值从一个Enum构造函数移动到下一个构造函数?

如何在函数中返回自定义字符串引用?

rust中的库插件管理器,现在是否可行?

Rust ndarray:如何从索引中 Select 数组的行

borrow 是由于对 `std::sync::Mutex>` 的解引用强制而发生的

如何将一个矩阵的列分配给另一个矩阵,纳尔代数?

Rust中如何实现一个与Sized相反的负特性(Unsized)

如何使用 Rust Governor 为每 10 秒 10 个请求创建一个 RateLimiter?

从 Axum IntoResponse 获取请求标头

&str 的编译时拆分是否可能?

没有分号的返回表达式的性能是否比使用返回更好?在Rust ?

为什么 std::iter::Peekable::peek 可变地borrow self 参数?

在 Rust 中组合特征的不同方法是否等效?

为移动和借位的所有组合实现 Add、Sub、Mul、Div