Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

How do I make an HTTP request from Rust?

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 HTTP response code.

Bonus marks if someone can show me how to URL encode the query parameters on my URL!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The easiest way to do HTTP in Rust is reqwest. It is a wrapper to make Hyper easier to use.

Hyper is a popular HTTP library for Rust which utilizes the Tokio event loop to make non-blocking requests. This relies on the futures crate for futures. A Hyper-based example is below and is largely inspired by an example in its documentation.

use hyper::{Client, Uri};

#[tokio::main]
async fn main() {
    let client = Client::new();

    let url: Uri = "http://httpbin.org/response-headers?foo=bar"
        .parse()
        .unwrap();
    assert_eq!(url.query(), Some("foo=bar"));

    match client.get(url).await {
        Ok(res) => println!("Response: {}", res.status()),
        Err(err) => println!("Error: {}", err),
    }
}

In Cargo.toml:

[dependencies]
tokio = { version = "0.2.21", features = ["macros"] }
hyper = "0.13.5"

Original answer (Rust 0.6)

I believe what you're looking for is in the standard library. now in rust-http and Chris Morgan's answer is the standard way in current Rust for the foreseeable future. I'm not sure how far I can take you (and hope I'm not taking you the wrong direction!), but you'll want something like:

// Rust 0.6 -- old code
extern mod std;

use std::net_ip;
use std::uv;

fn main() {
    let iotask = uv::global_loop::get();
    let result = net_ip::get_addr("www.duckduckgo.com", &iotask);

    io::println(fmt!("%?", result));
}

As for encoding, there are some examples in the unit tests in src/libstd/net_url.rs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...