I am trying to write the contents of an HTTP Response to a file.
extern crate reqwest;
use std::io::Write;
use std::fs::File;
fn main() {
let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
assert!(resp.status().is_success());
// Write contents to disk.
let mut f = File::create("download_file").expect("Unable to create file");
f.write_all(resp.bytes());
}
But I get the following compile error:
error[E0308]: mismatched types
--> src/main.rs:12:17
|
12 | f.write_all(resp.bytes());
| ^^^^^^^^^^^^ expected &[u8], found struct `std::io::Bytes`
|
= note: expected type `&[u8]`
found type `std::io::Bytes<reqwest::Response>`
We split the input integer (5000) into each byte by using the >> operator. The second operand represents the lowest bit index for each byte in the array. To obtain the 8 least significant bits for each byte, we & the result with 0xFF . Finally, we print each byte using the print function.
A Bytes handle can be created directly from an existing byte store (such as &[u8] or Vec<u8> ), but usually a BytesMut is used first and written to. For example: use bytes::{BytesMut, BufMut}; let mut buf = BytesMut::with_capacity(1024); buf.
u8 : The 8-bit unsigned integer type. u16 : The 16-bit unsigned integer type. u32 : The 32-bit unsigned integer type. u64 : The 64-bit unsigned integer type.
You cannot. Checking the docs for io::Bytes
, there are no appropriate methods. That's because io::Bytes
is an iterator that returns things byte-by-byte so there may not even be a single underlying slice of data.
It you only had io::Bytes
, you would need to collect
the iterator into a Vec
:
let data: Result<Vec<_>, _> = resp.bytes().collect();
let data = data.expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");
However, in most cases you have access to the type that implements Read
, so you could instead use Read::read_to_end
:
let mut data = Vec::new();
resp.read_to_end(&mut data).expect("Unable to read data");
f.write_all(&data).expect("Unable to write data");
In this specific case, you can use io::copy
to directly copy from the Request
to the file because Request
implements io::Read
and File
implements io::Write
:
extern crate reqwest;
use std::io;
use std::fs::File;
fn main() {
let mut resp = reqwest::get("https://www.rust-lang.org").unwrap();
assert!(resp.status().is_success());
// Write contents to disk.
let mut f = File::create("download_file").expect("Unable to create file");
io::copy(&mut resp, &mut f).expect("Unable to copy data");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With