Search code examples
rustreqwest

How to keep both body and headers from a response when using Reqwest?


let req: Request = client.get("https://someaddress").build().unwrap();
let resp = client.execute(req).await.unwrap();
let response_headers = resp.headers();
let response_text = resp.text().await.unwrap(); // cannot move out of `resp` because it is borrowed move out of `resp` occurs here

If text() and headers() both consume the response, how are we to ever get both the response headers and response body?


Solution

  • Getting the headers will not consume the response, but rather return a reference to the HeaderMap stored in the response. But getting the body will consume the response meaning any reference to it would be invalid, and thus you get an error trying to keep both.

    To keep both, you can simply clone the headers:

    let response_headers = resp.headers().clone();
    

    Or to avoid duplicating data, you can "take" the headers out of the response:

    let mut resp = client.execute(req).await.unwrap();
    let response_headers = std::mem::take(resp.headers_mut());
    let response_text = resp.text().await.unwrap();
    

    Using std::mem::take will pull the value out of the &mut from .headers_mut() and leave a default, empty HeaderMap in its place.

    Either method will mean response_headers is no longer referencing the response and you can happily get the body without worry of losing them.