How do I make an HTTP request from Rust?

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

    Building upon Patrik Stas' answer, if you want to do an HTTP form URL-encoded POST, here is what you have to do. In this case, it's to get an OAuth client_credentials token.

    Cargo.toml

    [dependencies]
    reqwest = "0.10.4"
    tokio = { version = "0.2.21", features = ["macros"] }
    

    Code

    use reqwest::{Client, Method};
    
    type Error = Box<dyn std::error::Error>;
    type Result<T, E = Error> = std::result::Result<T, E>;
    
    async fn print_access_token() -> Result<()> {
        let client = Client::new();
        let host = "login.microsoftonline.com";
        let tenant = "TENANT";
        let client_id = "CLIENT_ID";
        let client_secret = "CLIENT_SECRET";
        let scope = "https://graph.microsoft.com/.default";
        let grant_type = "client_credentials";
    
        let url_string = format!("https://{}/{}/oauth2/v2.0/token", host, tenant);
        let body = format!(
            "client_id={}&client_secret={}&scope={}&grant_type={}",
            client_id, client_secret, scope, grant_type,
        );
        let req = client.request(Method::POST, &url_string).body(body);
    
        let res = req.send().await?;
        println!("{}", res.status());
    
        let body = res.bytes().await?;
    
        let v = body.to_vec();
        let s = String::from_utf8_lossy(&v);
        println!("response: {} ", s);
    
        Ok(())
    }
    
    #[tokio::main]
    async fn main() -> Result<()> {
        print_access_token().await?;
    
        Ok(())
    }
    

    This will print something like the following.

    200 OK
    response: {"token_type":"Bearer","expires_in":3599,"ext_expires_in":3599,"access_token":"ACCESS_TOKEN"} 
    
    0 讨论(0)
提交回复
热议问题