我正在尝试使用Hyper获取HTML页面的内容,并希望同步返回未来输出的结果。我意识到我本可以选择一个更好的例子,因为同步HTTP请求已经存在,但我更感兴趣的是是否能够从异步计算中返回值。
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio;
use futures::{future, Future, Stream};
use hyper::Client;
use hyper::Uri;
use hyper_tls::HttpsConnector;
use std::str;
fn scrap() -> Result<String, String> {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);
client
.get("https://hyper.rs".parse::<Uri>().unwrap())
.and_then(|res| {
res.into_body().concat2().and_then(|body| {
let s_body: String = str::from_utf8(&body).unwrap().to_string();
futures::future::ok(s_body)
})
}).map_err(|err| format!("Error scraping web page: {:?}", &err))
});
scraped_content.wait()
}
fn read() {
let scraped_content = future::lazy(|| {
let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, hyper::Body>(https);
client
.get("https://hyper.rs".parse::<Uri>().unwrap())
.and_then(|res| {
res.into_body().concat2().and_then(|body| {
let s_body: String = str::from_utf8(&body).unwrap().to_string();
println!("Reading body: {}", s_body);
Ok(())
})
}).map_err(|err| {
println!("Error reading webpage: {:?}", &err);
})
});
tokio::run(scraped_content);
}
fn main() {
read();
let content = scrap();
println!("Content = {:?}", &content);
}
这个示例代码已经编译通过,并且对 read()
的调用成功,但是对scrap()
的调用会导致以下错误信息的恐慌:
Content = Err("Error scraping web page: Error { kind: Execute, cause: None }")
我知道在调用future对象的.wait()
方法之前没有正确启动任务,但是我找不到正确的方法来启动它,甚至不确定是否可能。
futures = { version="0", features=["executor"] }
- Chris