Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous 如何将响应正文作为字符串读取?_Asynchronous_Rust_Hyper - Fatal编程技术网

Asynchronous 如何将响应正文作为字符串读取?

Asynchronous 如何将响应正文作为字符串读取?,asynchronous,rust,hyper,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(htt

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

到目前为止,我所尝试的:


    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? 
        }
    }
我不知道该怎么办?

根据答案是:

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

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

这对我使用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()
}

这对我使用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()
}

你试过了吗?它返回一个Bytes对象,您可以将其解列为&[u8],然后您可以将其解列为&[u8]。我还建议您是否更喜欢易用性而不是对hyper.yep的细粒度控制。是的,就是这样。您尝试过吗?它返回一个Bytes对象,您可以将其反求为&[u8],然后您可以将其反求为&[u8]。我还建议您是否更喜欢易用性而不是hyper.yep的细粒度控制,仅此而已。尽管它肯定可以以更好的方式解决。请注意,如果您已经在异步代码中,您应该将runtime.block_部分替换为另一个答案中所示的.await。即使它肯定可以以更好的方式解决。请注意,如果您已经在异步代码中,您应该将runtime.block_部分替换为另一个答案中所示的.await。