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

4
这个问题有几个答案(这里, 这里这里),但是它们都对我无效 :(
我到目前为止尝试过的方法:

    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? 
        }
    }

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


你尝试过使用to_bytes吗?它会返回一个Bytes对象,你可以将其解引用为&[u8],然后将其解释为utf-8 - justinas
如果您更喜欢易用性而不是对hyper进行细粒度控制,我还建议使用reqwest - justinas
是的,就是这样。 - nomad
2个回答

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()
}

在1.0版本中移除了hyper::body::to_bytes()方法,现在可以使用req.collect().await?.to_bytes();来替代(to_bytes()方法现在是不会失败的)。 - undefined

3

根据 justinas 给出的答案:

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

尽管它肯定可以用更好的方式解决。 - nomad
请注意,如果您已经在异步代码内部,应该使用.await来替换runtime.block_on的部分,就像在其他答案中所见。 - Alice Ryhl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接