如何在 Rust Hyper 中将响应正文读取为字符串?

nom*_*mad 5 asynchronous rust hyper

这个问题有几个答案(这里这里这里),但没有一个对我有用:(

到目前为止我尝试过的:


    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? 
        }
    }
Run Code Online (Sandbox Code Playgroud)

我不确定,在这里做什么?

cob*_*lla 8

这对我有用(使用 hyper 0.2.1):

async fn body_to_string(req: Request<Body>) -> String {
    let body_bytes = hyper::body::to_bytes(req.into_body()).await?;
    String::from_utf8(body_bytes.to_vec()).unwrap()
}
Run Code Online (Sandbox Code Playgroud)

  • hyper::body::to_bytes() 在 1.0 中被删除, `req.collect().await?.to_bytes();` 有效。(to_bytes() 现在不会出错) (2认同)

nom*_*mad 3

根据贾斯蒂纳斯的说法,答案是:

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