How do I make an HTTP request from Rust?

前端 未结 7 878
长情又很酷
长情又很酷 2020-12-02 12:04

How can I make an HTTP request from Rust? I can\'t seem to find anything in the core library.

I don\'t need to parse the output, just make a request and check the HT

7条回答
  •  执笔经年
    2020-12-02 12:44

    The easiest way to do HTTP in Rust is reqwest. It is a wrapper to make Hyper easier to use.

    Hyper is a popular HTTP library for Rust which utilizes the Tokio event loop to make non-blocking requests. This relies on the futures crate for futures. A Hyper-based example is below and is largely inspired by an example in its documentation.

    use hyper::{Client, Uri};
    
    #[tokio::main]
    async fn main() {
        let client = Client::new();
    
        let url: Uri = "http://httpbin.org/response-headers?foo=bar"
            .parse()
            .unwrap();
        assert_eq!(url.query(), Some("foo=bar"));
    
        match client.get(url).await {
            Ok(res) => println!("Response: {}", res.status()),
            Err(err) => println!("Error: {}", err),
        }
    }
    

    In Cargo.toml:

    [dependencies]
    tokio = { version = "0.2.21", features = ["macros"] }
    hyper = "0.13.5"
    

    Original answer (Rust 0.6)

    I believe what you're looking for is in the standard library. now in rust-http and Chris Morgan's answer is the standard way in current Rust for the foreseeable future. I'm not sure how far I can take you (and hope I'm not taking you the wrong direction!), but you'll want something like:

    // Rust 0.6 -- old code
    extern mod std;
    
    use std::net_ip;
    use std::uv;
    
    fn main() {
        let iotask = uv::global_loop::get();
        let result = net_ip::get_addr("www.duckduckgo.com", &iotask);
    
        io::println(fmt!("%?", result));
    }
    

    As for encoding, there are some examples in the unit tests in src/libstd/net_url.rs.

提交回复
热议问题