You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Rust从澳统计局下载Zip文件失败,Python代码可正常运行

问题解决:Rust reqwest下载ABS Zip文件仅获取70字节

问题原因

70字节的返回内容并非目标Zip文件,而是服务器返回的拦截提示或重定向响应。澳大利亚统计局(ABS)的服务器会验证请求的User-Agent头:

  • Python requests库的默认UA(如python-requests/2.31.0)被服务器允许访问,能正常获取完整文件;
  • Rust reqwest库的默认UA(如reqwest/0.11.22)被服务器识别为非标准客户端,拒绝返回完整资源。

修正后的Rust代码

添加服务器认可的User-Agent头即可解决问题:

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 response = client
        .get(url)
        // 使用浏览器风格的User-Agent,或python-requests的UA均可
        .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
        .send()
        .expect("Failed to send request");

    // 先验证状态码,避免直接unwrap引发 panic
    assert_eq!(response.status(), reqwest::StatusCode::OK, "Request failed with status: {}", response.status());
    
    let zip_bytes = response.bytes().expect("Failed to read response bytes");
    println!("Length: {}", zip_bytes.len());
}

example() // 现在会输出127525

排查技巧

如果后续仍有问题,可以先打印响应的状态码和文本内容,确认服务器返回的具体信息:

let response = client.get(url).header("User-Agent", "...").send().unwrap();
println!("Status Code: {}", response.status());
println!("Response Content: {}", response.text().unwrap());

内容的提问来源于stack exchange,提问作者Mark Graph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 10:32:38