asynchronousrusthyper

How to read the response body as a string in Rust Hyper?


This question has several answers (here, here, and here), but none of them worked for me :(

What I've tried so far:


    use hyper as http;
    use futures::TryStreamExt;

    fn test_heartbeat() {
        let mut runtime = tokio::runtime::Runtime::new().expect("Could not get default runtime");

        runtime.spawn(httpserve());

        let addr = "http://localhost:3030".parse().unwrap();
        let expected = json::to_string(&HeartBeat::default()).unwrap();

        let client = http::Client::new();
        let actual = runtime.block_on(client.get(addr));

        assert!(actual.is_ok());

        if let Ok(response) = actual {
            let (_, body) = response.into_parts();
            
            // what shall be done here? 
        }
    }

I am not sure, what to do here?


Solution

  • According to justinas the answer is:

    // ...
    let bytes = runtime.block_on(hyper::body::to_bytes(body)).unwrap();
    let result = String::from_utf8(bytes.into_iter().collect()).expect("");