[hyper] Getting http response body in a variable

I'm trying to save response of a HTTP request in a variable but i don't know how is it possible.
I'm using last version of hyper.

let res = "".to_string();
let work = client.request(req).and_then(|res| {
    println!("Response: {}", res.status());
    res.body()
        .for_each(|chunk| io::stdout().write_all(&chunk).map_err(From::from))
});
core.run(work).unwrap();

This is peace of code that just will print value in stdout. I would like store result in a variable like res;

Thanks.

Take a look at the json example: https://hyper.rs/guides/client/json/

Your case is very similar except you want to convert the bytes of the response to a String. If you also yield the String from the closure, then core.run(work).unwrap() will return you that String.

1 Like
let body_bytes = hyper::body::to_bytes(res.into_body()).await?;
let body = String::from_utf8(body_bytes.to_vec())?;

New link is here: Advanced Client Usage | hyper

This topic was automatically closed 30 days after the last reply. We invite you to open a new topic if you have further questions or comments.