Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HTTP proxy with asynchronous Hyper 0.11 in Rust?

How do I send an HTTP request using a proxy with Hyper 0.11? I have the following working code that sends an HTTP request without proxy:

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

This is not a duplicate of How to reach an HTTPS site via proxy with Hyper? because I am asking about the new version of Hyper 0.11 that has a totally different API which is not compatible with previous versions.

like image 531
Sergey Potapov Avatar asked Jul 26 '17 15:07

Sergey Potapov


1 Answers

You can use the Client::configure() method to build a proxy connector, and then build it with the handle, see below code snippet

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)

Now you can use the client object to perform any REST calls.

like image 192
Fei Avatar answered Nov 14 '22 17:11

Fei