How do I make an HTTP request from Rust?

前端 未结 7 897
长情又很酷
长情又很酷 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:33

    using hyper "0.13"

    also using hyper-tls for https support

    Cargo.toml

    hyper = "0.13"
    hyper-tls = "0.4.1"
    tokio = { version = "0.2", features = ["full"] }
    

    Code

    extern crate hyper;
    use hyper::Client;
    use hyper::body::HttpBody as _;
    use tokio::io::{stdout, AsyncWriteExt as _};
    use hyper_tls::HttpsConnector;
    
    #[tokio::main]
    async fn main() -> Result<(), Box> {
    
        // http only
        // let client = Client::new(); 
    
        // http or https connections
        let client = Client::builder().build::<_, hyper::Body>(HttpsConnector::new());
    
        let mut resp = client.get("https://catfact.ninja/fact".parse()?).await?;
    
        println!("Response: {}", resp.status());
    
        while let Some(chunk) = resp.body_mut().data().await {
            stdout().write_all(&chunk?).await?;
        }
    
        Ok(())
    }
    

    adapted from https://hyper.rs/guides/client/basic/

提交回复
热议问题