如何在Rust中使用异步Hyper 0.11与HTTP代理?

19

我如何在Hyper 0.11中使用代理发送HTTP请求?我有以下可以发送不使用代理的HTTP请求的工作代码:

extern crate hyper;
extern crate tokio_core;
extern crate futures;

use futures::Future;
use hyper::Client;
use tokio_core::reactor::Core;

fn main() {
    let mut core = Core::new().unwrap();
    let client = Client::new(&core.handle());

    let uri = "http://stackoverflow.com".parse().unwrap();
    let work = client.get(uri).map(|res| {
        res.status()
    });

    match core.run(work) {
        Ok(status) => println!("Status: {}", status),
        Err(e) => println!("Error: {:?}", e)
    }
}

这不是重复的问题如何通过Hyper代理访问HTTPS站点?,因为我询问的是全新的Hyper 0.11版本,其具有完全不兼容以前版本的API。


3
您可能会在作者基于hyper 0.11开发的高级接口中找到很多灵感,该接口名为reqwest https://github.com/seanmonstar/reqwest/blob/master/src/proxy.rs - softprops
Sergey,上面的例子有帮助吗? - Mario Idival
我放弃了那个话题,还没有尝试过它们。 - Sergey Potapov
1个回答

2
您可以使用Client::configure()方法构建代理连接器,然后使用handle进行构建,如下面的代码片段所示。
let handle = core.handle();
let proxy = {
    let proxy_uri ="http://<your proxy>:port".parse().unwrap();
    let mut proxy = Proxy::new(Intercept::All, proxy_uri);
    proxy.set_authorization(Basic{
        username: "your username",
        password: Some("your passwd"),
    }); 
    let http_connector = HttpConnector::new(4, &handle);
    ProxyConnector::from_proxy(http_connector, proxy).unwrap()
};
let client = Client::configure().connector(proxy).build(&handle)

现在您可以使用客户端对象执行任何 REST 调用。

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