Make a get #HTTP Request in #Rust using #Curl
There are plenty of examples of making a HTTP request using Rust online, but so many of them gloss over very important details, like how to import the library you need to make the request, and for a beginner, it’s not really helpful to give a snippet of code without the surrounding instructions. Plus, it appears that perhaps there are different versions of code that just aren’t backwards compatible. This example works on
rustc 1.19.0 (0ade33941 2017-07-17)
If you have a different version, then, I can’t guarantee this works, but try it anyway.
First off, you need to install Cargo, I am using cargo version
cargo 0.20.0 (a60d185c8 2017-07-13)
Create a new cargo project called http by typing
cargo new http — bin
Then edit the cargo.toml file, and add the CURL dependency here;
[dependencies]
curl = “0.2.11”
now, edit the main.rs file, and add this code;
extern crate curl;
use curl::http;
// Thanks to https://github.com/hjr3/rust-get-data-from-url
pub fn main() {let url = “http://icanhazip.com/”;
let resp = http::handle()
.get(url)
.exec()
.unwrap_or_else(|e| {
panic!(“Failed to get {}; error is {}”, url, e);
});if resp.get_code() != 200 {
println!(“Unable to handle HTTP response code {}”, resp.get_code());
return;
}let body = std::str::from_utf8(resp.get_body()).unwrap_or_else(|e| {
panic!(“Failed to parse response from {}; error is {}”, url, e);
});println!(“{}”,body);
}
What this does, is it makes a CURL get HTTP request to http://icanhazip.com/ , which simply returns the IP address of the client (you), and prints it to screen.
To run it, type cargo build, then
./target/debug/http
:::Update:::
Ok, being a bit of a noob here, I have noticed, that this example is quite dated, using CURL version 0.2.11, when the latest is 0.4.8 ; but you have to change the code completely to use version 0.4.8
First, update the cargo.toml to
[dependencies]
curl = “0.4.8”
Then the main.rs to
extern crate curl;
use curl::easy::{Easy, List};
// Capture output into a local `Vec`.
fn main() {
let mut easy = Easy::new();
easy.url(“http://icanhazip.com”).unwrap();let mut html: String = String::new();
{
let mut transfer = easy.transfer();
transfer.write_function(|data| {
html = String::from_utf8(Vec::from(data)).unwrap();
Ok(data.len())
}).unwrap();transfer.perform().unwrap();
};
println!(“{}”,html);
}