1

我正在尝试将 a 转换Result为 a Buffer

let ufc_root: String =
    String::from("https://www.ufc.com/athletes/all?filters%5B0%5D=status%3A23");
// let ufc_root: String = String::from("https://www.google.com");
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);

client
    .get(ufc_root.parse::<hyper::Uri>().unwrap())
    .and_then(|res| {
        println!("http status code: {}", res.status());
        println!("http response headers:\n{:?}: ", res.headers());
        res.into_body()
    })
    .from_err::<WebScrapeError>()
    .and_then(|body| {
        body.for_each(|chunk| {
            println!("{}", chunk.into_bytes());
        });

        let jon_jones = Subject {
            name: "Jon Jones".to_string(),
            link: "http://www.jonjones.com".to_string(),
        };
        let subjects = vec![jon_jones];
        Ok(subjects)
    })
    .from_err()
error[E0277]: the trait bound `hyper::Body: hyper::rt::Future` is not satisfied
  --> src/scrapper.rs:24:14
   |
24 |             .and_then(|res| {
   |              ^^^^^^^^ the trait `hyper::rt::Future` is not implemented for `hyper::Body`
   |
   = note: required because of the requirements on the impl of `futures::future::IntoFuture` for `hyper::Body`

error[E0599]: no method named `from_err` found for type `futures::future::and_then::AndThen<hyper::client::ResponseFuture, hyper::Body, [closure@src/scrapper.rs:24:23: 28:14]>` in the current scope
  --> src/scrapper.rs:29:14
   |
29 |             .from_err::<WebScrapeError>()
   |              ^^^^^^^^
   |
   = note: the method `from_err` exists but the following trait bounds were not satisfied:
           `&mut futures::future::and_then::AndThen<hyper::client::ResponseFuture, hyper::Body, [closure@src/scrapper.rs:24:23: 28:14]> : hyper::rt::Future`
           `&mut futures::future::and_then::AndThen<hyper::client::ResponseFuture, hyper::Body, [closure@src/scrapper.rs:24:23: 28:14]> : hyper::rt::Stream`
           `futures::future::and_then::AndThen<hyper::client::ResponseFuture, hyper::Body, [closure@src/scrapper.rs:24:23: 28:14]> : hyper::rt::Future`

为什么不编译?

4

1 回答 1

5

and_then必须返回一个未来,或者可以通过IntoFuturetrait 转换为未来的东西。你回来res.into_body()了,这不是一个未来——它实际上是一个流

要使其工作,您需要将该流转换为代表已完全读取主体的未来。这里有几个选项可供您使用:

  • res.into_body().concat2(),它将所有读取的字节连接到一个缓冲区中
  • res.into_body().collect(),它将所有字节块收集到一个Vec
  • res.into_body().into_future(),它将解析为一个元组,其中包含流中的第一项,以及流本身的其余部分(即(T, Stream<Item = T>)

Stream将 a 表示为 a有多种不同(且同样有效)的方式,这一事实Future很可能是前者没有全面实现IntoFuture.

Hyper 文档concat2中显示了一个使用示例。

于 2019-03-19T09:44:06.423 回答