Reqwest: async equivalent of `std::io::copy(&mut response, &mut other)`

Created on 30 Apr 2020  路  5Comments  路  Source: seanmonstar/reqwest

In the blocking version of reqwest (v0.9) it was possible to do:

let mut temp = tempfile::NamedTempFile::new().unwrap();
let mut response = reqwest::get("...").await.unwrap();
std::io::copy(&mut response, &mut temp).unwrap();

but this is no longer a possibility in the async API (as of v0.10) since Response no longer implements std::io::Read. What's the async/await equivalent? Really I just want to be able to download a file.

Most helpful comment

This should work

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::get("http://httpbin.org/get").await?;
    let bytes = resp.bytes().await?;
    let mut out = tokio::fs::File::create("file.tmp").await?;
    tokio::io::copy(&mut &*bytes, &mut out).await?;
    Ok(())
}

Cargo.toml

[dependencies]
reqwest = "0.10"
tokio = { version = "0.2", features = ["full"] }

All 5 comments

Also the relevant example in the cookbook is outdated.

I have the same problem. The copy function() expects something that implements the Read trait. I tried the bytes() method, but the result is not Read.

How could we convert an async response to something that is Read?

i know nothing about async rust but, maybe this example from async-std can help.
I think that as you start using async you can't use sync api function from standart anymore , but their equivalent in async-std.
I hope someone will correct me if i said something wrong

This should work

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let resp = reqwest::get("http://httpbin.org/get").await?;
    let bytes = resp.bytes().await?;
    let mut out = tokio::fs::File::create("file.tmp").await?;
    tokio::io::copy(&mut &*bytes, &mut out).await?;
    Ok(())
}

Cargo.toml

[dependencies]
reqwest = "0.10"
tokio = { version = "0.2", features = ["full"] }

Exactly, I came up with a similar solution using tokio async files from https://docs.rs/tokio/0.2.20/tokio/fs/struct.File.html

no need to use full tokio, the fs addition is enough:

tokio = { version = "0.2", features = ["fs"] }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

29e7e280-0d1c-4bba-98fe-f7cd3ca7500a picture 29e7e280-0d1c-4bba-98fe-f7cd3ca7500a  路  6Comments

martinlindhe picture martinlindhe  路  3Comments

silvioprog picture silvioprog  路  5Comments

theduke picture theduke  路  6Comments

amesgen picture amesgen  路  6Comments