How do you make a GET request in Rust?

I noticed that Rust does not have a built-in library for working with HTTP, it only has a net module that deals with raw IP and TCP protocols.

I need to take the &str URLs, make a GET HTTP request, and if successful return either String or &str , which matches HTML or JSON or another answer in string form.

It will look something like this:

 use somelib::http; let response = http::get(&"http://stackoverflow.com"); match response { Some(suc) => suc, None => panic! } 
+12
source share
3 answers

Look at Hyper .

Submitting a GET request is as simple as that.

 let client = Client::new(); let res = client.get("http://example.domain").send().unwrap(); assert_eq!(res.status, hyper::Ok); 

You can find more examples in the documentation .

Edit : It seems that Hyper has become a bit more complicated since they started using Tokio . Here is the updated version.

 extern crate futures; extern crate hyper; extern crate tokio_core; use std::io::{self, Write}; use futures::{Future, Stream}; 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://httpbin.org/ip".parse().unwrap(); let work = client.get(uri).and_then(|res| { println!("Response: {}", res.status()); res.body().for_each(|chunk| { io::stdout() .write_all(&chunk) .map_err(From::from) }) }); core.run(work).unwrap(); } 

And here are the required dependencies.

 [dependencies] futures = "0.1" hyper = "0.11" tokio-core = "0.1" 
+10
source

Currently, to solve this specific reqwest problem reqwest use the reqwest mailbox as indicated in the Rust Cookbook . This code is slightly adapted from the cookbook to run autonomously:

 extern crate reqwest; // 0.9.18 use std::io::Read; fn run() -> Result<(), Box<dyn std::error::Error>> { let mut res = reqwest::get("http://httpbin.org/get")?; let mut body = String::new(); res.read_to_string(&mut body)?; println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers()); println!("Body:\n{}", body); Ok(()) } 

As the cookbook mentions, this code will execute synchronously.

See also:

+5
source

Try switching to reqwest:

 extern crate reqwest; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut res = reqwest::get("https://httpbin.org/headers")?; // copy the response body directly to stdout std::io::copy(&mut res, &mut std::io::stdout())?; Ok(()) } 
-1
source

Source: https://habr.com/ru/post/1266340/


All Articles