Reqwest Response is not a Read

I was downloading some image data using reqwest:

let resp = reqwest::blocking::get(url).unwrap();
let mut picture = Picture::read_from(resp).unwrap();

Picture::read_from() expects an std::io::Read which reqwest::blocking::Response implements.

Now something else was changed in the code and my reqwest::blocking::get() no longer works (Cannot drop a runtime in a context where blocking is not allowed).

So I'm converting my code from reqwest::blocking to reqwest.

The normal reqwest::Response doesn't implement std::io::Read, so I tried this instead:

let resp = reqwest::get(url).await.unwrap();
let mut picture = Picture::read_from(resp.bytes().await.unwrap()).unwrap();

But now I'm getting the trait std::io::Read is not implemented for bytes::bytes::Bytes.

Do I need to wrap the Bytes in a Cursor or something or am I using reqwest wrong?

Try Bytes::as_ref().
It returns a &[u8] which is Read.

let mut picture = Picture::read_from(resp.bytes().await.unwrap().as_ref()).unwrap();

Alternatively, use Bytes::reader().

std::io::Read is itself a blocking API, so you should not be using it either. You need to move this code so that it is in a 'context where blocking is allowed' — e.g. spawn_blocking() or your own thread created for the purpose. That's the only way to make this work and still operate in a streaming fashion (assuming that Picture provides no async alternative).

1 Like