Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a GET request in Rust?

Tags:

I noticed that Rust doesn't have a builtin library to deal with HTTP, it only has a net module that deals with raw IP and TCP protocols.

I need to take a &str of the URL, make a HTTP GET request, and if successful return either a String or &str that corresponds to the HTML or JSON or other response in string form.

It would look something like:

use somelib::http;

let response = http::get(&"http://stackoverflow.com");
match response {
    Some(suc) => suc,
    None => panic!
}
like image 931
Josh Weinstein Avatar asked Apr 05 '17 05:04

Josh Weinstein


People also ask

How does a GET request work?

A GET request, in simple terms, is a way for you to grab data from a data source with the help of the internet. It's done using the GET request method, which is a very common HTTP request method (like POST, PUT, or DELETE). Despite the capitalization, “GET” is not an acronym, so it doesn't stand for anything.

What does a GET request contain?

The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.


2 Answers

Take a look at Hyper.

Sending a GET request is as simple as this.

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 got a bit more complicated since they started to use Tokio. Here is 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"
like image 66
Januson Avatar answered Oct 03 '22 11:10

Januson


The current best practice for this particular problem is to use the reqwest crate, as specified in the Rust Cookbook. This code is slightly adapted from the cookbook to run standalone:

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 be executed synchronously.

See also:

  • How can I perform parallel asynchronous HTTP GET requests with reqwest?
like image 34
nindalf Avatar answered Oct 03 '22 11:10

nindalf