在Rust中执行HTTP的最简单方法是reqwest。 它是使Hyper易于使用的包装。
Hyper是Rust常用的HTTP库,它使用两个库:Tokio的事件循环(用于发出非阻塞请求)和Futures-rs(用于期货/承诺)。 下面是一个基于Hyper的示例,其灵感主要来自其文档中的示例。
// Rust 1.36, Hyper 0.12.35, tokio-core 0.1.17, futures 0.1.29
extern crate futures;
extern crate hyper;
extern crate tokio_core;
use futures::{Future};
use hyper::{Client, Uri};
use tokio_core::reactor::Core;
fn main() {
// Core is the Tokio event loop used for making a non-blocking request
let mut core = Core::new().unwrap();
let client = Client::new();
let url : Uri = "http://httpbin.org/response-headers?foo=bar".parse().unwrap();
assert_eq!(url.query(), Some("foo=bar"));
let request_result = core.run(client
.get(url)
.map(|res| {
println!("Response: {}", res.status());
})
.map_err(|err| {
println!("Error: {}", err);
})
);
}
在Cargo.toml中:
[dependencies]
hyper = "0.12.35"
tokio-core = "0.1.17"
futures = "0.1.29"
为了后代,我在下面保留了我的原始答案,但请参见上面的Rust 1.19(最新的稳定版本)更新在撰写本文时)。
我相信您正在寻找的是标准库。 现在在rust-http中使用,而Chris Morgan的回答是在可预见的将来当前Rust的标准方法。我不确定我能带您走多远(并希望我不会带错方向!),但是您会想要以下东西:
// 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));
}
*/
至于编码,在src / libstd / net_url.rs中的单元测试中有一些示例。